diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..4cadb26b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +.gitattributes eol=lf +.gitmodules eol=lf diff --git a/.gitignore b/.gitignore index b147f35b..2b92be95 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,10 @@ *.userprefs *.pidb *.gmo +*.bak +*.suo +*.sln.cache +*.user po/POTFILES Makefile.in Makefile @@ -20,6 +24,8 @@ config.sub INSTALL aclocal.m4 autom4te.cache/ +bin/ +obj/ /bin/ SparkleShare/Mac/bin install-sh @@ -33,7 +39,9 @@ SparkleLib/AssemblyInfo.cs build/m4/shave/shave build/m4/*.m4 build/m4/shave/shave-libtool -Defines.cs +SparkleLib/Defines.cs +SparkleLib/windows/Defines.cs +SparkleLib/windows/GlobalAssemblyInfo.cs SparkleShare/sparkleshare po/sparkleshare.pot SparkleShare/Nautilus/sparkleshare-nautilus-extension.py @@ -41,3 +49,5 @@ SparkleShare/Nautilus/sparkleshare-nautilus3-extension.py gnome-doc-utils.make /sparkleshare-* data/plugins/*.xml +desktop.ini +_ReSharper.* diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..e69de29b diff --git a/AUTHORS b/AUTHORS index fb3bb87c..5aa038cf 100755 --- a/AUTHORS +++ b/AUTHORS @@ -40,6 +40,7 @@ Contributors: Travis Glenn Hansen Vincent Untz Will Thompson + Konstantinos Vaggelakos Thanks very much! diff --git a/LICENSE.rtf b/LICENSE.rtf new file mode 100644 index 00000000..f679cc67 --- /dev/null +++ b/LICENSE.rtf @@ -0,0 +1,115 @@ +{\rtf1\ansi\ansicpg1252\deff0\deflang2077{\fonttbl{\f0\froman\fcharset0 Times New Roman;}{\f1\fnil\fcharset0 Calibri;}{\f2\fnil\fcharset2 Symbol;}} +{\colortbl ;\red0\green0\blue255;} +{\*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\keepn\sb100\sa100\lang1053\b\f0\fs28 GNU GENERAL PUBLIC LICENSE\par +\pard\sb100\sa100\b0\fs24 Version 3, 29 June 2007\par +Copyright \'a9 2007 Free Software Foundation, Inc. <{\field{\*\fldinst{HYPERLINK "http://fsf.org/"}}{\fldrslt{\ul\cf1 http://fsf.org/}}}\f0\fs24 >\par +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\par +\pard\keepn\sb100\sa100\b\fs28 Preamble\par +\pard\sb100\sa100\b0\fs24 The GNU General Public License is a free, copyleft license for software and other kinds of works.\par +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.\par +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 them 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.\par +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.\par +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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.\par +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.\par +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.\par +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.\par +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.\par +The precise terms and conditions for copying, distribution and modification follow.\par +\pard\keepn\sb100\sa100\b\fs28 TERMS AND CONDITIONS\par +\fs24 0. Definitions.\par +\pard\sb100\sa100\b0\ldblquote This License\rdblquote refers to version 3 of the GNU General Public License.\par +\ldblquote Copyright\rdblquote also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.\par +\ldblquote The Program\rdblquote refers to any copyrightable work licensed under this License. Each licensee is addressed as \ldblquote you\rdblquote . \ldblquote Licensees\rdblquote and \ldblquote recipients\rdblquote may be individuals or organizations.\par +To \ldblquote modify\rdblquote a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a \ldblquote modified version\rdblquote of the earlier work or a work \ldblquote based on\rdblquote the earlier work.\par +A \ldblquote covered work\rdblquote means either the unmodified Program or a work based on the Program.\par +To \ldblquote propagate\rdblquote a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.\par +To \ldblquote convey\rdblquote a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.\par +An interactive user interface displays \ldblquote Appropriate Legal Notices\rdblquote to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.\par +\pard\keepn\sb100\sa100\b 1. Source Code.\par +\pard\sb100\sa100\b0 The \ldblquote source code\rdblquote for a work means the preferred form of the work for making modifications to it. \ldblquote Object code\rdblquote means any non-source form of a work.\par +A \ldblquote Standard Interface\rdblquote means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.\par +The \ldblquote System Libraries\rdblquote of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A \ldblquote Major Component\rdblquote , in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.\par +The \ldblquote Corresponding Source\rdblquote for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.\par +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\par +The Corresponding Source for a work in source code form is that same work.\par +\pard\keepn\sb100\sa100\b 2. Basic Permissions.\par +\pard\sb100\sa100\b0 All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.\par +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.\par +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.\par +\pard\keepn\sb100\sa100\b 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\par +\pard\sb100\sa100\b0 No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.\par +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.\par +\pard\keepn\sb100\sa100\b 4. Conveying Verbatim Copies.\par +\pard\sb100\sa100\b0 You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.\par +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.\par +\pard\keepn\sb100\sa100\b 5. Conveying Modified Source Versions.\par +\pard\sb100\sa100\b0 You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:\par +\pard{\pntext\f2\'B7\tab}{\*\pn\pnlvlblt\pnf2\pnindent360{\pntxtb\'B7}}\fi-360\li720\sb100\sa100 a) The work must carry prominent notices stating that you modified it, and giving a relevant date. \par +{\pntext\f2\'B7\tab}b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to \ldblquote keep intact all notices\rdblquote . \par +{\pntext\f2\'B7\tab}c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. \par +{\pntext\f2\'B7\tab}d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. \par +\pard\sb100\sa100 A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an \ldblquote aggregate\rdblquote if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.\par +\pard\keepn\sb100\sa100\b 6. Conveying Non-Source Forms.\par +\pard\sb100\sa100\b0 You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:\par +\pard{\pntext\f2\'B7\tab}{\*\pn\pnlvlblt\pnf2\pnindent360{\pntxtb\'B7}}\fi-360\li720\sb100\sa100 a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. \par +{\pntext\f2\'B7\tab}b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. \par +{\pntext\f2\'B7\tab}c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. \par +{\pntext\f2\'B7\tab}d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. \par +{\pntext\f2\'B7\tab}e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. \par +\pard\sb100\sa100 A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.\par +A \ldblquote User Product\rdblquote is either (1) a \ldblquote consumer product\rdblquote , which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, \ldblquote normally used\rdblquote refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.\par +\ldblquote Installation Information\rdblquote for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.\par +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).\par +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.\par +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.\par +\pard\keepn\sb100\sa100\b 7. Additional Terms.\par +\pard\sb100\sa100\b0\ldblquote Additional permissions\rdblquote are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.\par +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.\par +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:\par +\pard{\pntext\f2\'B7\tab}{\*\pn\pnlvlblt\pnf2\pnindent360{\pntxtb\'B7}}\fi-360\li720\sb100\sa100 a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or \par +{\pntext\f2\'B7\tab}b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or \par +{\pntext\f2\'B7\tab}c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or \par +{\pntext\f2\'B7\tab}d) Limiting the use for publicity purposes of names of licensors or authors of the material; or \par +{\pntext\f2\'B7\tab}e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or \par +{\pntext\f2\'B7\tab}f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. \par +\pard\sb100\sa100 All other non-permissive additional terms are considered \ldblquote further restrictions\rdblquote within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.\par +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.\par +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.\par +\pard\keepn\sb100\sa100\b 8. Termination.\par +\pard\sb100\sa100\b0 You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).\par +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.\par +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.\par +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.\par +\pard\keepn\sb100\sa100\b 9. Acceptance Not Required for Having Copies.\par +\pard\sb100\sa100\b0 You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.\par +\pard\keepn\sb100\sa100\b 10. Automatic Licensing of Downstream Recipients.\par +\pard\sb100\sa100\b0 Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.\par +An \ldblquote entity transaction\rdblquote is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.\par +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.\par +\pard\keepn\sb100\sa100\b 11. Patents.\par +\pard\sb100\sa100\b0 A \ldblquote contributor\rdblquote is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's \ldblquote contributor version\rdblquote .\par +A contributor's \ldblquote essential patent claims\rdblquote are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, \ldblquote control\rdblquote includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.\par +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.\par +In the following three paragraphs, a \ldblquote patent license\rdblquote is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To \ldblquote grant\rdblquote such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.\par +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. \ldblquote Knowingly relying\rdblquote means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.\par +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.\par +A patent license is \ldblquote discriminatory\rdblquote if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.\par +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.\par +\pard\keepn\sb100\sa100\b 12. No Surrender of Others' Freedom.\par +\pard\sb100\sa100\b0 If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.\par +\pard\keepn\sb100\sa100\b 13. Use with the GNU Affero General Public License.\par +\pard\sb100\sa100\b0 Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.\par +\pard\keepn\sb100\sa100\b 14. Revised Versions of this License.\par +\pard\sb100\sa100\b0 The Free Software Foundation may publish revised and/or new versions of the GNU 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.\par +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License \ldblquote or any later version\rdblquote applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.\par +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.\par +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.\par +\pard\keepn\sb100\sa100\b 15. Disclaimer of Warranty.\par +\pard\sb100\sa100\b0 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 \ldblquote AS IS\rdblquote 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.\par +\pard\keepn\sb100\sa100\b 16. Limitation of Liability.\par +\pard\sb100\sa100\b0 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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.\par +\pard\keepn\sb100\sa100\b 17. Interpretation of Sections 15 and 16.\par +\pard\sb100\sa100\b0 If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.\par +END OF TERMS AND CONDITIONS\lang29\f1\fs22\par +} + \ No newline at end of file diff --git a/README.md b/README.md index 1ee2d861..34daa038 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,33 @@ Copy `/Library/Frameworks/Mono.framework/Versions/Current/lib/libintl.dylib` to Now you should have a working bundle that you can run. +## Build on Windows + +* Install [.NET Framework 4.0](http://www.microsoft.com/download/en/details.aspx?id=17851) (if not installed yet) + +* Install [msysGit](http://code.google.com/p/msysgit/downloads/detail?name=Git-1.7.8-preview20111206.exe) + * Change install location to `C:\msysgit` (location is hard-coded in the build scrits) + * Use default settings for all other questions during installation + +* Copy the entire contents of the msysGit folder to `{clone folder}\bin\msysgit` + +* _Build step_: Open a command shell (available in Start Menu > Accessories > Command Prompt) and execute (Note to Windows 7 x64 users: change the WinDirNet variable in build.cmd to "%WinDir%\Microsoft.NET\Framework64") + + C: + cd {clone folder} + cd SparkleShare\Windows + build + +* `{clone folder}\bin` should now contain `SparkleLib.dll` and `SparkleShare.exe`, apart from folders `plugins`, `po` and `msysgit` + +* If you want to build the Windows installer download and install [WiX 3.6](http://wix.sourceforge.net/) + +* _Installer build step_: Then open a command shell and write almost the same as before, but with `installer` at the end + + C: + cd {clone folder} + cd SparkleShare\Windows + build installer ## Info diff --git a/SparkleLib/Git/SparkleFetcherGit.cs b/SparkleLib/Git/SparkleFetcherGit.cs index 00af578e..31e3b24d 100755 --- a/SparkleLib/Git/SparkleFetcherGit.cs +++ b/SparkleLib/Git/SparkleFetcherGit.cs @@ -94,7 +94,7 @@ namespace SparkleLib { this.git = new SparkleGit (SparkleConfig.DefaultConfig.TmpPath, "clone " + "--progress " + // Redirects progress stats to standarderror - "\"" + RemoteUrl + "\" " + "\"" + TargetFolder + "\""); + "\"" + RemoteUrl + "\" " + "\"" + SparkleHelpers.NormalizeSeparatorsToOS(TargetFolder) + "\""); this.git.StartInfo.RedirectStandardError = true; this.git.Start (); diff --git a/SparkleLib/Git/SparkleRepoGit.cs b/SparkleLib/Git/SparkleRepoGit.cs old mode 100755 new mode 100644 index a68cb9ab..471d33b3 --- a/SparkleLib/Git/SparkleRepoGit.cs +++ b/SparkleLib/Git/SparkleRepoGit.cs @@ -560,7 +560,7 @@ namespace SparkleLib { List change_sets = new List (); // Console.InputEncoding = System.Text.Encoding.Unicode; - Console.OutputEncoding = System.Text.Encoding.Unicode; + // Console.OutputEncoding = System.Text.Encoding.Unicode; SparkleGit git_log = new SparkleGit (LocalPath, "log -" + count + " --raw -M --date=iso"); git_log.Start (); diff --git a/SparkleLib/SparkleConfig.cs b/SparkleLib/SparkleConfig.cs index d6a6915a..8e02e978 100755 --- a/SparkleLib/SparkleConfig.cs +++ b/SparkleLib/SparkleConfig.cs @@ -189,8 +189,14 @@ namespace SparkleLib { string ssh_config_path = Path.Combine (path, ".ssh"); string ssh_config_file_path = SparkleHelpers.CombineMore (path, ".ssh", "config"); - string ssh_config = "IdentityFile " + - Path.Combine (SparkleConfig.ConfigPath, "sparkleshare." + User.Email + ".key"); + + string ssh_key_path = SparkleHelpers.NormalizeSeparatorsToOS( + Path.Combine(SparkleConfig.ConfigPath, "sparkleshare." + User.Email + ".key")); + if (SparkleHelpers.IsWindows && ssh_key_path.IndexOf(' ') >= 0) + { + ssh_key_path = "\"" + ssh_key_path + "\""; + } + string ssh_config = "IdentityFile " + ssh_key_path; if (!Directory.Exists (ssh_config_path)) Directory.CreateDirectory (ssh_config_path); diff --git a/SparkleLib/SparkleHelpers.cs b/SparkleLib/SparkleHelpers.cs index 7b262d80..e86424ab 100755 --- a/SparkleLib/SparkleHelpers.cs +++ b/SparkleLib/SparkleHelpers.cs @@ -98,6 +98,29 @@ namespace SparkleLib { { return target.Replace (source + Path.DirectorySeparatorChar, ""); } + + public static bool IsWindows + { + get + { + PlatformID platform = Environment.OSVersion.Platform; + return (platform == PlatformID.Win32NT + || platform == PlatformID.Win32S + || platform == PlatformID.Win32Windows); + } + } + + public static string NormalizeSeparatorsToOS(string path) + { + if (IsWindows) + { + return path.Replace('\\', '/'); + } + else + { + return path; + } + } } } diff --git a/SparkleLib/SparkleListenerTcp.cs b/SparkleLib/SparkleListenerTcp.cs index 24ec0f70..1810a065 100755 --- a/SparkleLib/SparkleListenerTcp.cs +++ b/SparkleLib/SparkleListenerTcp.cs @@ -159,7 +159,7 @@ namespace SparkleLib { this.is_connected = false; this.is_connecting = false;; - if (this.socket != null) + if (this.socket != null) this.socket.Close (); OnDisconnected ("Ping timeout"); diff --git a/SparkleLib/windows/AssemblyInfo.cs b/SparkleLib/windows/AssemblyInfo.cs new file mode 100644 index 00000000..9d14d314 --- /dev/null +++ b/SparkleLib/windows/AssemblyInfo.cs @@ -0,0 +1,14 @@ +/* + * AssemblyInfo.cs + * + * This is free software. See COPYING for details. + */ + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle ("SparkleLib")] +[assembly: AssemblyDescription ("SparkleShare is a simple file sharing and collaboration tool.")] + +[assembly: Guid ("38092E48-5DCC-4d23-8109-9D994E710ACF")] diff --git a/SparkleLib/windows/Defines.tt b/SparkleLib/windows/Defines.tt new file mode 100644 index 00000000..ffbc5538 --- /dev/null +++ b/SparkleLib/windows/Defines.tt @@ -0,0 +1,46 @@ +// SparkleShare, an instant update workflow to Git. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can 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 . + +<#@ template language="C#v3.5" HostSpecific="true" #> +<#@ output extension="cs" #> + +<#@ include file="getversion.tt" #> + +<# + PlatformID platform = Environment.OSVersion.Platform; + bool IsWindows = (platform == PlatformID.Win32NT + || platform == PlatformID.Win32S + || platform == PlatformID.Win32Windows + || platform == PlatformID.WinCE); +#> + +using System; + +namespace SparkleLib { + + public class Defines { + + public const string VERSION = "<#= VERSION #>"; + public const string LOCALE_DIR = "@prefix@/share/locale"; + public const string DATAROOTDIR = "@expanded_datadir@"; + public const string GETTEXT_PACKAGE = "@GETTEXT_PACKAGE@"; + public const string PREFIX = "@prefix@"; + public const string OPEN_COMMAND = "xdg-open"; + + } + +} + diff --git a/SparkleLib/windows/GlobalAssemblyInfo.tt b/SparkleLib/windows/GlobalAssemblyInfo.tt new file mode 100644 index 00000000..104f2caf --- /dev/null +++ b/SparkleLib/windows/GlobalAssemblyInfo.tt @@ -0,0 +1,25 @@ +/* + * GlobalAssemblyInfo.cs + * + * This is free software. See COPYING for details. + */ +<#@ template language="C#v3.5" HostSpecific="true" #> +<#@ output extension="cs" #> + +<#@ include file="getversion.tt" #> + +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyProduct("SparkleShare")] + +[assembly: AssemblyVersion("<#= ASM_VERSION #>")] +[assembly: AssemblyFileVersion("<#= ASM_FILE_VERSION #>")] +[assembly: AssemblyInformationalVersion("<#= VERSION #>")] + +#if DEBUG +[assembly: AssemblyConfiguration("Debug")] +#else +[assembly: AssemblyConfiguration("Release")] +#endif + diff --git a/SparkleLib/windows/SparkleLib.csproj b/SparkleLib/windows/SparkleLib.csproj new file mode 100644 index 00000000..2db89ec8 --- /dev/null +++ b/SparkleLib/windows/SparkleLib.csproj @@ -0,0 +1,176 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {2C914413-B31C-4362-93C7-1AE34F09112A} + Library + SparkleLib + SparkleLib + + + 3.5 + + + false + v3.5 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + true + full + false + ..\..\bin + DEBUG + prompt + 4 + false + x86 + AllRules.ruleset + + + none + false + ..\..\bin + prompt + 4 + false + AllRules.ruleset + x86 + + + + + 3.5 + + + + + + SparkleFetcherGit.cs + + + SparkleGit.cs + Component + + + SparkleRepoGit.cs + + + SparkleAnnouncement.cs + + + SparkleConfig.cs + + + SparkleExtensions.cs + + + SparkleListenerFactory.cs + + + SparkleRepoBase.cs + + + SparkleUser.cs + + + SparkleWatcher.cs + Component + + + + Defines.tt + Code + True + True + + + + + + + + + True + True + GlobalAssemblyInfo.tt + + + + + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 2.0 %28x86%29 + true + + + False + .NET Framework 3.0 %28x86%29 + false + + + False + .NET Framework 3.5 + false + + + False + .NET Framework 3.5 SP1 + false + + + + + TextTemplatingFileGenerator + Defines.cs + + + TextTemplatingFileGenerator + GlobalAssemblyInfo.cs + + + + + + + + + + + + + + + + + + + + + $(ProjectDir)transform_tt.cmd + + \ No newline at end of file diff --git a/SparkleLib/windows/getversion.tt b/SparkleLib/windows/getversion.tt new file mode 100644 index 00000000..7aa89216 --- /dev/null +++ b/SparkleLib/windows/getversion.tt @@ -0,0 +1,41 @@ +<#@ import namespace="System" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Text.RegularExpressions" #> + +<# + // Add msysgit to path, as we cannot asume it is added to the path + // Asume it is installed in @"C:\msysgit\bin" for now + string MSysGit=@"C:\msysgit"; + + string newPath = MSysGit + @"\bin" + ";" + + MSysGit + @"\mingw\bin" + ";" + + MSysGit + @"\cmd" + ";" + + System.Environment.ExpandEnvironmentVariables ("%PATH%"); + System.Environment.SetEnvironmentVariable ("PATH", newPath); + + Process process = new Process(); + process.StartInfo.UseShellExecute = false; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.CreateNoWindow = true; + process.StartInfo.FileName = "git"; + process.StartInfo.Arguments = "describe --tags"; + process.StartInfo.WorkingDirectory = Path.GetDirectoryName(Host.TemplateFile); + process.Start(); + + String DescribeOutput=process.StandardOutput.ReadLine(); + + Match m = Regex.Match(DescribeOutput, @"(\d+)\.(\d+)(?:-rc(\d+))?-(\d+)"); + int[] version = new int [4]; + for(int i=1; i <= 4; i++) + Int32.TryParse(m.Groups[i].Value, out version[i-1]); + + String VERSION=DescribeOutput; + String ASM_VERSION=String.Format("{0}.{1}",version[0],version[1]); + String ASM_FILE_VERSION=String.Format("{0}.{1}.{2}.{3}",version[0],version[1],version[2],version[3]); + +#> + +// VERSION=<#= VERSION #> +// ASM_VERSION=<#= ASM_VERSION #> + diff --git a/SparkleLib/windows/transform_tt.cmd b/SparkleLib/windows/transform_tt.cmd new file mode 100644 index 00000000..3ba9ef60 --- /dev/null +++ b/SparkleLib/windows/transform_tt.cmd @@ -0,0 +1,11 @@ +@echo off +cd %~dp0 + +set TextTransform=..\..\SparkleShare\Windows\tools\TextTemplating\bin\TextTransform.exe +if not exist %TextTransform% call ..\..\SparkleShare\Windows\tools\TextTemplating\build.cmd + +echo running texttransform.. + +%TextTransform% -out Defines.cs Defines.tt +%TextTransform% -out GlobalAssemblyInfo.cs GlobalAssemblyInfo.tt + diff --git a/SparkleShare/Program.cs b/SparkleShare/Program.cs old mode 100755 new mode 100644 diff --git a/SparkleShare/SparkleControllerBase.cs b/SparkleShare/SparkleControllerBase.cs old mode 100755 new mode 100644 index ec5bd2dd..b06a8dc8 --- a/SparkleShare/SparkleControllerBase.cs +++ b/SparkleShare/SparkleControllerBase.cs @@ -27,7 +27,9 @@ using System.Text.RegularExpressions; using System.Threading; using System.Xml; +#if __MonoCS__ using Mono.Unix; +#endif using SparkleLib; namespace SparkleShare { @@ -121,7 +123,7 @@ namespace SparkleShare { // Short alias for the translations public static string _ (string s) { - return Catalog.GetString (s); + return Program._(s); } @@ -1131,14 +1133,18 @@ namespace SparkleShare { } - public void Quit () + public virtual void Quit () { lock (this.repo_lock) { foreach (SparkleRepoBase repo in Repositories) repo.Dispose (); } +#if __MonoCS__ Environment.Exit (0); +#else + System.Windows.Forms.Application.Exit(); +#endif } diff --git a/SparkleShare/SparkleExtensions.cs b/SparkleShare/SparkleExtensions.cs old mode 100755 new mode 100644 diff --git a/SparkleShare/SparkleStatusIcon.cs b/SparkleShare/SparkleStatusIcon.cs old mode 100755 new mode 100644 diff --git a/SparkleShare/SparkleUI.cs b/SparkleShare/SparkleUI.cs old mode 100755 new mode 100644 index e533fb03..17618ce2 --- a/SparkleShare/SparkleUI.cs +++ b/SparkleShare/SparkleUI.cs @@ -23,9 +23,13 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading; +#if __MonoCS__ using Gtk; using Mono.Unix; using Mono.Unix.Native; +#else +using System.Windows.Forms; +#endif using SparkleLib; namespace SparkleShare { @@ -45,17 +49,19 @@ namespace SparkleShare { // Short alias for the translations public static string _(string s) { - return Catalog.GetString (s); + return Program._ (s); } public SparkleUI () { // Initialize the application +#if __MonoCS__ Application.Init (); // Use translations Catalog.Init (Defines.GETTEXT_PACKAGE, Defines.LOCALE_DIR); +#endif Setup = new SparkleSetup (); EventLog = new SparkleEventLog (); @@ -72,6 +78,7 @@ namespace SparkleShare { public void Run () { Application.Run (); + StatusIcon.Dispose (); } } } diff --git a/SparkleShare/Windows/ApplicationSchemeHandler.cs b/SparkleShare/Windows/ApplicationSchemeHandler.cs new file mode 100644 index 00000000..bb7d8237 --- /dev/null +++ b/SparkleShare/Windows/ApplicationSchemeHandler.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using CefSharp; +using System.IO; + +namespace SparkleShare { + + class ApplicationSchemeHandler : ISchemeHandler { + #region ISchemeHandler Members + + public bool ProcessRequest (IRequest request, ref string mimeType, ref Stream stream) + { + if (request.Url.EndsWith (".png")) { + System.Drawing.Bitmap Image=null; + + if (request.Url.EndsWith ("avatar-default-32.png")) + Image = Icons.avatar_default_32; + else if (request.Url.EndsWith ("document-added-12.png")) + Image = Icons.document_added_12; + else if (request.Url.EndsWith ("document-edited-12.png")) + Image = Icons.document_edited_12; + else if (request.Url.EndsWith ("document-deleted-12.png")) + Image = Icons.document_deleted_12; + else if (request.Url.EndsWith ("document-moved-12.png")) + Image = Icons.document_moved_12; + + if (Image != null) { + stream = new MemoryStream (); + Image.Save (stream, System.Drawing.Imaging.ImageFormat.Png); + stream.Seek (0, SeekOrigin.Begin); + mimeType = "image/png"; + return true; + } + } else if (request.Url.EndsWith (".js")) { + string Text = null; + + if (request.Url.EndsWith ("jquery.js")) + Text = Properties.Resources.jquery_js; + + if (Text != null) { + stream = new MemoryStream (Encoding.UTF8.GetPreamble ().Concat (Encoding.UTF8.GetBytes (Text)).ToArray ()); + mimeType = "application/javascript"; + return true; + } + } + + return false; + } + + #endregion + } + + public class ApplicationSchemeHandlerFactory : ISchemeHandlerFactory { + public ISchemeHandler Create () + { + return new ApplicationSchemeHandler (); + } + } + +} diff --git a/SparkleShare/Windows/AssemblyInfo.cs b/SparkleShare/Windows/AssemblyInfo.cs new file mode 100644 index 00000000..092685d9 --- /dev/null +++ b/SparkleShare/Windows/AssemblyInfo.cs @@ -0,0 +1,14 @@ +/* + * AssemblyInfo.cs + * + * This is free software. See COPYING for details. + */ + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle ("SparkleShare")] +[assembly: AssemblyDescription ("SparkleShare is a simple file sharing and collaboration tool.")] + +[assembly: Guid ("A8F34995-DB20-4bf2-AA27-869B15B8C2F9")] diff --git a/SparkleShare/Windows/FileSchemeHandler.cs b/SparkleShare/Windows/FileSchemeHandler.cs new file mode 100644 index 00000000..0984447f --- /dev/null +++ b/SparkleShare/Windows/FileSchemeHandler.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using CefSharp; +using System.IO; + +namespace SparkleShare { + + class FileSchemeHandler : ISchemeHandler { + #region ISchemeHandler Members + + public bool ProcessRequest (IRequest request, ref string mimeType, ref Stream stream) + { + return false; + } + + #endregion + } + + public class FileSchemeHandlerFactory : ISchemeHandlerFactory { + public ISchemeHandler Create () + { + return new FileSchemeHandler (); + } + } +} diff --git a/SparkleShare/Windows/Icons.Designer.cs b/SparkleShare/Windows/Icons.Designer.cs new file mode 100644 index 00000000..5eacec98 --- /dev/null +++ b/SparkleShare/Windows/Icons.Designer.cs @@ -0,0 +1,308 @@ +//------------------------------------------------------------------------------ +// +// Este código fue generado por una herramienta. +// Versión del motor en tiempo de ejecución:2.0.50727.3625 +// +// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si +// se vuelve a generar el código. +// +//------------------------------------------------------------------------------ + +namespace SparkleShare { + using System; + + + /// + /// Clase de recurso con establecimiento inflexible de tipos, para buscar cadenas traducidas, etc. + /// + // StronglyTypedResourceBuilder generó automáticamente esta clase + // a través de una herramienta como ResGen o Visual Studio. + // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen + // con la opción /str o vuelva a generar su proyecto de VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Icons { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Icons() { + } + + /// + /// Devuelve la instancia de ResourceManager almacenada en caché utilizada por esta clase. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SparkleShare.Icons", typeof(Icons).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Reemplaza la propiedad CurrentUICulture del subproceso actual para todas las + /// búsquedas de recursos mediante esta clase de recurso con establecimiento inflexible de tipos. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + internal static System.Drawing.Bitmap about { + get { + object obj = ResourceManager.GetObject("about", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap avatar_default { + get { + object obj = ResourceManager.GetObject("avatar_default", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap avatar_default_16 { + get { + object obj = ResourceManager.GetObject("avatar_default_16", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap avatar_default_22 { + get { + object obj = ResourceManager.GetObject("avatar_default_22", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap avatar_default_24 { + get { + object obj = ResourceManager.GetObject("avatar_default_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap avatar_default_32 { + get { + object obj = ResourceManager.GetObject("avatar_default_32", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap avatar_default_48 { + get { + object obj = ResourceManager.GetObject("avatar_default_48", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap dialog_error_16 { + get { + object obj = ResourceManager.GetObject("dialog_error_16", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap dialog_error_24 { + get { + object obj = ResourceManager.GetObject("dialog_error_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap document_added_12 { + get { + object obj = ResourceManager.GetObject("document_added_12", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap document_deleted_12 { + get { + object obj = ResourceManager.GetObject("document_deleted_12", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap document_edited_12 { + get { + object obj = ResourceManager.GetObject("document_edited_12", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap document_moved_12 { + get { + object obj = ResourceManager.GetObject("document_moved_12", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap folder_sparkleshare_16 { + get { + object obj = ResourceManager.GetObject("folder_sparkleshare_16", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap folder_sparkleshare_22 { + get { + object obj = ResourceManager.GetObject("folder_sparkleshare_22", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap folder_sparkleshare_24 { + get { + object obj = ResourceManager.GetObject("folder_sparkleshare_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap folder_sparkleshare_256 { + get { + object obj = ResourceManager.GetObject("folder_sparkleshare_256", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap folder_sparkleshare_32 { + get { + object obj = ResourceManager.GetObject("folder_sparkleshare_32", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap folder_sparkleshare_48 { + get { + object obj = ResourceManager.GetObject("folder_sparkleshare_48", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap list_point_16 { + get { + object obj = ResourceManager.GetObject("list_point_16", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap process_syncing_sparkleshare_24 { + get { + object obj = ResourceManager.GetObject("process_syncing_sparkleshare_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap process_syncing_sparkleshare_i_24 { + get { + object obj = ResourceManager.GetObject("process_syncing_sparkleshare_i_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap process_syncing_sparkleshare_ii_24 { + get { + object obj = ResourceManager.GetObject("process_syncing_sparkleshare_ii_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap process_syncing_sparkleshare_iii_24 { + get { + object obj = ResourceManager.GetObject("process_syncing_sparkleshare_iii_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap process_syncing_sparkleshare_iiii_24 { + get { + object obj = ResourceManager.GetObject("process_syncing_sparkleshare_iiii_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap process_syncing_sparkleshare_iiiii_24 { + get { + object obj = ResourceManager.GetObject("process_syncing_sparkleshare_iiiii_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap process_working_22 { + get { + object obj = ResourceManager.GetObject("process_working_22", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap side_splash { + get { + object obj = ResourceManager.GetObject("side_splash", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Icon sparkleshare { + get { + object obj = ResourceManager.GetObject("sparkleshare", resourceCulture); + return ((System.Drawing.Icon)(obj)); + } + } + + internal static System.Drawing.Bitmap sparkleshare_syncing_error_24 { + get { + object obj = ResourceManager.GetObject("sparkleshare_syncing_error_24", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap sparkleshare_windows_status { + get { + object obj = ResourceManager.GetObject("sparkleshare_windows_status", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap tutorial_slide_1 { + get { + object obj = ResourceManager.GetObject("tutorial_slide_1", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap tutorial_slide_2 { + get { + object obj = ResourceManager.GetObject("tutorial_slide_2", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap tutorial_slide_3 { + get { + object obj = ResourceManager.GetObject("tutorial_slide_3", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap tutorial_slide_4 { + get { + object obj = ResourceManager.GetObject("tutorial_slide_4", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/SparkleShare/Windows/Icons.resx b/SparkleShare/Windows/Icons.resx new file mode 100644 index 00000000..09b2f988 --- /dev/null +++ b/SparkleShare/Windows/Icons.resx @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\..\data\icons\avatar-default-16.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\avatar-default-22.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\avatar-default-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\avatar-default-32.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\avatar-default-48.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\avatar-default.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\dialog-error-16.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\dialog-error-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\document-added-12.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\document-deleted-12.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\document-edited-12.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\document-moved-12.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\folder-sparkleshare-16.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\folder-sparkleshare-22.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\folder-sparkleshare-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\folder-sparkleshare-256.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\folder-sparkleshare-32.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\folder-sparkleshare-48.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\list-point-16.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\process-syncing-sparkleshare-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\process-syncing-sparkleshare-i-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\process-syncing-sparkleshare-ii-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\process-syncing-sparkleshare-iii-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\process-syncing-sparkleshare-iiii-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\process-syncing-sparkleshare-iiiii-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\process-working-22.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\sparkleshare-syncing-error-24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\sparkleshare-windows-status.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\icons\sparkleshare.ico;System.Drawing.Icon, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\about.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\side-splash.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\tutorial-slide-1.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\tutorial-slide-2.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\tutorial-slide-3.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\..\data\tutorial-slide-4.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/SparkleShare/Windows/Icons.tt b/SparkleShare/Windows/Icons.tt new file mode 100644 index 00000000..ef4bcb83 --- /dev/null +++ b/SparkleShare/Windows/Icons.tt @@ -0,0 +1,168 @@ + +<#@ template language="C#v3.5" HostSpecific="true" #> +<#@ output extension="resx" #> +<#@ import namespace="System" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Text.RegularExpressions" #> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + <# + string RelativeDir = @"..\..\data\icons"; + DirectoryInfo dir = new DirectoryInfo(RelativeDir); + + foreach (FileInfo f in dir.GetFiles("*.png")) + { + string DataName = Regex.Replace(Path.ChangeExtension(f.Name, null), "[^a-zA-Z0-9_]", "_"); + string FileName = Path.Combine(RelativeDir, f.Name); + #> + + <#= FileName #>;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + <# + } + + foreach (FileInfo f in dir.GetFiles("*.ico")) + { + string DataName = Regex.Replace(Path.ChangeExtension(f.Name, null), "[^a-zA-Z0-9_]", "_"); + string FileName = Path.Combine(RelativeDir, f.Name); + #> + + <#= FileName #>;System.Drawing.Icon, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + <# + } + + RelativeDir = @"..\..\data"; + dir = new DirectoryInfo(RelativeDir); + + foreach (FileInfo f in dir.GetFiles("*.png")) + { + string DataName = Regex.Replace(Path.ChangeExtension(f.Name, null), "[^a-zA-Z0-9_]", "_"); + string FileName = Path.Combine(RelativeDir, f.Name); + #> + + <#= FileName #>;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + <# + } + + #> + diff --git a/SparkleShare/Windows/Notification.cs b/SparkleShare/Windows/Notification.cs new file mode 100644 index 00000000..e7f7bc3e --- /dev/null +++ b/SparkleShare/Windows/Notification.cs @@ -0,0 +1,128 @@ +// SparkleShare, an instant update workflow to Git. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can 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 . + + +using System; +using System.Windows.Forms; +using System.Drawing; +using System.IO; + + +namespace Notifications +{ + public partial class Notification : Form + { + private Timer animationTimer; + private int startPosX; + private int startPosY; + + //public new Gdk.Pixbuf Icon; + + public Notification () + { + InitializeComponent (); + + TopMost = true; + ShowInTaskbar = false; + + animationTimer = new Timer (); + animationTimer.Interval = 50; + animationTimer.Tick += timer_Tick; + } + + public Notification (string title, string subtext) + : this() + { + this.title.Text = title; + this.subtext.Text = subtext; + } + + protected override void OnLoad (EventArgs e) + { + // Move window out of screen + startPosX = Screen.PrimaryScreen.WorkingArea.Width - Width; + startPosY = Screen.PrimaryScreen.WorkingArea.Height; + SetDesktopLocation (startPosX, startPosY); + base.OnLoad (e); + // Begin animation + animationTimer.Start (); + } + + protected override void OnShown (EventArgs e) + { + base.OnShown (e); + + // hacky way to move the image from a Gdk.Pixbuf to a winforms bitmap + string Filename = Path.GetTempFileName (); + File.Delete (Filename); + + Filename = Path.ChangeExtension (Filename, "bmp"); + if (File.Exists (Filename)) + File.Delete (Filename); + //this.Icon.Save (Filename, "bmp"); + using (Stream s = File.OpenRead (Filename)) + pictureBox1.Image = Bitmap.FromStream (s); + File.Delete (Filename); + } + + void timer_Tick (object sender, EventArgs e) + { + startPosY -= 5; + + if (startPosY < Screen.PrimaryScreen.WorkingArea.Height - Height) + animationTimer.Stop (); + else + SetDesktopLocation (startPosX, startPosY); + } + + public void AddAction (string action, string label, ActionHandler handler) + { + } + + public void RemoveAction (string action) + { + } + + public void ClearActions () + { + } + + } + + public enum Urgency : byte + { + Low = 0, + Normal, + Critical + } + + public class ActionArgs : EventArgs + { + private string action; + public string Action + { + get { return action; } + } + + public ActionArgs (string action) + { + this.action = action; + } + } + + public delegate void ActionHandler (object o, ActionArgs args); + +} diff --git a/SparkleShare/Windows/Notification.designer.cs b/SparkleShare/Windows/Notification.designer.cs new file mode 100644 index 00000000..a3d36c82 --- /dev/null +++ b/SparkleShare/Windows/Notification.designer.cs @@ -0,0 +1,96 @@ +namespace Notifications +{ + partial class Notification + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.pictureBox1 = new System.Windows.Forms.PictureBox (); + this.title = new System.Windows.Forms.Label (); + this.subtext = new System.Windows.Forms.Label (); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit (); + this.SuspendLayout (); + // + // pictureBox1 + // + this.pictureBox1.Location = new System.Drawing.Point (12, 12); + this.pictureBox1.Name = "pictureBox1"; + this.pictureBox1.Size = new System.Drawing.Size (40, 42); + this.pictureBox1.TabIndex = 0; + this.pictureBox1.TabStop = false; + // + // title + // + this.title.AutoSize = true; + this.title.Font = new System.Drawing.Font ("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.title.Location = new System.Drawing.Point (58, 9); + this.title.Name = "title"; + this.title.Size = new System.Drawing.Size (28, 13); + this.title.TabIndex = 1; + this.title.Text = "title"; + // + // subtext + // + this.subtext.AutoSize = true; + this.subtext.Location = new System.Drawing.Point (58, 22); + this.subtext.MaximumSize = new System.Drawing.Size (171, 0); + this.subtext.Name = "subtext"; + this.subtext.Size = new System.Drawing.Size (41, 13); + this.subtext.TabIndex = 2; + this.subtext.Text = "subtext"; + // + // Notification + // + this.AutoScaleDimensions = new System.Drawing.SizeF (6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size (241, 64); + this.ControlBox = false; + this.Controls.Add (this.subtext); + this.Controls.Add (this.title); + this.Controls.Add (this.pictureBox1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "Notification"; + this.Opacity = 0.8; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit (); + this.ResumeLayout (false); + this.PerformLayout (); + + } + + #endregion + + private System.Windows.Forms.PictureBox pictureBox1; + private System.Windows.Forms.Label title; + private System.Windows.Forms.Label subtext; + + } +} + diff --git a/SparkleShare/Windows/Notification.resx b/SparkleShare/Windows/Notification.resx new file mode 100644 index 00000000..19dc0dd8 --- /dev/null +++ b/SparkleShare/Windows/Notification.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SparkleShare/Windows/Program.cs b/SparkleShare/Windows/Program.cs new file mode 100644 index 00000000..2e43ea4d --- /dev/null +++ b/SparkleShare/Windows/Program.cs @@ -0,0 +1,172 @@ +// SparkleShare, a collaboration and sharing tool. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can 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 . + + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; + +#if __MonoCS__ +using Mono.Unix; +//using Mono.Unix.Native; +#endif +using SparkleLib; + +namespace SparkleShare { + + // This is SparkleShare! + public class Program { + + public static SparkleController Controller; + public static SparkleUI UI; + + + // Short alias for the translations + public static string _ (string s) + { +#if __MonoCS__ + return Catalog.GetString (s); +#else + return Strings.T(s); +#endif + } + +#if !__MonoCS__ + public static void TranslateWinForm (System.Windows.Forms.Form form) + { + form.Text = Program._ (form.Text); + + foreach (var label in form.Controls.All ().OfType ()) { + label.Text = Program._ (label.Text); + } + foreach (var button in form.Controls.All ().OfType ()) { + button.Text = Program._ (button.Text); + } + } +#endif + +#if !__MonoCS__ + [STAThread] +#endif + public static void Main (string [] args) + { + SetUiCulture(); + + // Parse the command line options + bool show_help = false; + OptionSet option_set = new OptionSet () { + { "v|version", _("Print version information"), v => { PrintVersion (); } }, + { "h|help", _("Show this help text"), v => show_help = v != null } + }; + + try { + option_set.Parse (args); + + } catch (OptionException e) { + Console.Write ("SparkleShare: "); + Console.WriteLine (e.Message); + Console.WriteLine ("Try `sparkleshare --help' for more information."); + } + + if (show_help) + ShowHelp (option_set); + + + // Initialize the controller this way so that + // there aren't any exceptions in the OS specific UI's + Controller = new SparkleController (); + Controller.Initialize (); + + if (Controller != null) { + UI = new SparkleUI (); + UI.Run (); + } + +#if !__MonoCS__ + // For now we must do GC.Collect to free some internal handles, otherwise + // in debug mode you can got assertion message. + GC.Collect (GC.MaxGeneration, GCCollectionMode.Forced); + GC.WaitForPendingFinalizers (); + CefSharp.CEF.Shutdown (); // Shutdown CEF. +#endif + } + + public static void SetUiCulture() + { + //var culture = CultureInfo.GetCultureInfo ("en"); // FIXME: test only + //System.Threading.Thread.CurrentThread.CurrentUICulture = culture; + } + + + // Prints the help output + public static void ShowHelp (OptionSet option_set) + { + Console.WriteLine (" "); + Console.WriteLine (_("SparkleShare, a collaboration and sharing tool.")); + Console.WriteLine (_("Copyright (C) 2010 Hylke Bons")); + Console.WriteLine (" "); + Console.WriteLine (_("This program comes with ABSOLUTELY NO WARRANTY.")); + Console.WriteLine (" "); + Console.WriteLine (_("This is free software, and you are welcome to redistribute it ")); + Console.WriteLine (_("under certain conditions. Please read the GNU GPLv3 for details.")); + Console.WriteLine (" "); + Console.WriteLine (_("SparkleShare automatically syncs Git repositories in ")); + Console.WriteLine (_("the ~/SparkleShare folder with their remote origins.")); + Console.WriteLine (" "); + Console.WriteLine (_("Usage: sparkleshare [start|stop|restart] [OPTION]...")); + Console.WriteLine (_("Sync SparkleShare folder with remote repositories.")); + Console.WriteLine (" "); + Console.WriteLine (_("Arguments:")); + + option_set.WriteOptionDescriptions (Console.Out); + Environment.Exit (0); + } + + + // Prints the version information + public static void PrintVersion () + { + Console.WriteLine (_("SparkleShare " + Defines.VERSION)); + Environment.Exit (0); + } + +#if __MonoCS__ + // Strange magic needed by SetProcessName () + [DllImport ("libc")] + private static extern int prctl (int option, byte [] arg2, IntPtr arg3, IntPtr arg4, IntPtr arg5); +#endif + + // Sets the Unix process name to 'sparkleshare' instead of 'mono' + private static void SetProcessName (string name) + { +#if __MonoCS__ + try { + if (prctl (15, Encoding.ASCII.GetBytes (name + "\0"), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) != 0) + throw new ApplicationException ("Error setting process name: " + + Mono.Unix.Native.Stdlib.GetLastError ()); + + } catch (EntryPointNotFoundException) { + Console.WriteLine ("SetProcessName: Entry point not found"); + } +#endif + } + } +} diff --git a/SparkleShare/Windows/Properties/Resources.Designer.cs b/SparkleShare/Windows/Properties/Resources.Designer.cs new file mode 100644 index 00000000..844f818e --- /dev/null +++ b/SparkleShare/Windows/Properties/Resources.Designer.cs @@ -0,0 +1,150 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50727.3053 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace SparkleShare.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SparkleShare.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to <div class='day-entry'> + /// <div class='day-entry-header'> + /// <!-- $day-entry-header --> + /// </div> + /// <div class='day-entry-content'> + /// <!-- $day-entry-content --> + /// </div> + ///</div> + ///. + /// + internal static string day_entry_html { + get { + return ResourceManager.GetString("day_entry_html", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to <div class='event-entry' style='background-image: url("<!-- $event-avatar-url -->");'> + /// <div class='event-user-name'><!-- $event-user-name --></div> + /// <div class='event-folder'><!-- $event-folder --></div> + /// + /// <!-- $event-entry-content --> + /// + /// <div class="clearer"></div> + /// <div class="event-timestamp"><!-- $event-time --></div> + /// <div class="action note">Add note</div> + /// <div class="action show">Show all</div> + /// + /// <div class="clearer"></div> + /// + /// <div class="comments-section"> + /// [rest of string was truncated]";. + /// + internal static string event_entry_html { + get { + return ResourceManager.GetString("event_entry_html", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to <!doctype html> + ///<html> + /// <head> + /// <title>SparkleShare Event Log</title> + /// <script type="text/javascript" src="<!-- $jquery-url -->"></script> + /// <script type="text/javascript"> + /// $(document).ready(function () { + /// $('.comments-section').each (function () { + /// if ($(this).find ('.comments').children ().size () < 1) { + /// $(this).hide (); + /// } + /// }); + /// + /// $('.buddy-icon').each (function () { + /// [rest of string was truncated]";. + /// + internal static string event_log_html { + get { + return ResourceManager.GetString("event_log_html", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /*! + /// * jQuery JavaScript Library v1.6.1 + /// * http://jquery.com/ + /// * + /// * Copyright 2011, John Resig + /// * Dual licensed under the MIT or GPL Version 2 licenses. + /// * http://jquery.org/license + /// * + /// * Includes Sizzle.js + /// * http://sizzlejs.com/ + /// * Copyright 2011, The Dojo Foundation + /// * Released under the MIT, BSD, and GPL Licenses. + /// * + /// * Date: Thu May 12 15:04:36 2011 -0400 + /// */ + ///(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!cj[a]){var [rest of string was truncated]";. + /// + internal static string jquery_js { + get { + return ResourceManager.GetString("jquery_js", resourceCulture); + } + } + } +} diff --git a/SparkleShare/Windows/Properties/Resources.resx b/SparkleShare/Windows/Properties/Resources.resx new file mode 100644 index 00000000..ff560fa0 --- /dev/null +++ b/SparkleShare/Windows/Properties/Resources.resx @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\..\..\data\html\day-entry.html;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 + + + ..\..\..\data\html\event-entry.html;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 + + + ..\..\..\data\html\event-log.html;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 + + + ..\..\..\data\html\jquery.js;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 + + \ No newline at end of file diff --git a/SparkleShare/Windows/SparkleAbout.Designer.cs b/SparkleShare/Windows/SparkleAbout.Designer.cs new file mode 100644 index 00000000..a65acdd6 --- /dev/null +++ b/SparkleShare/Windows/SparkleAbout.Designer.cs @@ -0,0 +1,105 @@ +namespace SparkleShare { + partial class SparkleAbout { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager (typeof (SparkleAbout)); + this.version = new System.Windows.Forms.Label (); + this.copyright = new System.Windows.Forms.Label (); + this.emptyLabel = new System.Windows.Forms.Label (); + this.SparkleShareVersion = new System.Windows.Forms.Label (); + this.SuspendLayout (); + // + // version + // + this.version.AutoSize = true; + this.version.BackColor = System.Drawing.Color.Transparent; + this.version.ForeColor = System.Drawing.Color.LightGray; + this.version.Location = new System.Drawing.Point (302, 102); + this.version.Name = "version"; + this.version.Size = new System.Drawing.Size (34, 13); + this.version.TabIndex = 1; + this.version.Text = "........."; + // + // copyright + // + this.copyright.BackColor = System.Drawing.Color.Transparent; + this.copyright.Font = new System.Drawing.Font ("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.copyright.ForeColor = System.Drawing.Color.White; + this.copyright.Location = new System.Drawing.Point (302, 135); + this.copyright.Name = "copyright"; + this.copyright.Size = new System.Drawing.Size (298, 84); + this.copyright.TabIndex = 2; + this.copyright.Text = resources.GetString ("copyright.Text"); + // + // emptyLabel + // + this.emptyLabel.AutoSize = true; + this.emptyLabel.Location = new System.Drawing.Point (16, 89); + this.emptyLabel.Name = "emptyLabel"; + this.emptyLabel.Size = new System.Drawing.Size (0, 13); + this.emptyLabel.TabIndex = 6; + // + // SparkleShareVersion + // + this.SparkleShareVersion.AutoSize = true; + this.SparkleShareVersion.BackColor = System.Drawing.Color.Transparent; + this.SparkleShareVersion.ForeColor = System.Drawing.Color.White; + this.SparkleShareVersion.Location = new System.Drawing.Point (302, 89); + this.SparkleShareVersion.Name = "SparkleShareVersion"; + this.SparkleShareVersion.Size = new System.Drawing.Size (106, 13); + this.SparkleShareVersion.TabIndex = 1; + this.SparkleShareVersion.Text = "SparkleShareVersion"; + // + // SparkleAbout + // + this.AutoScaleDimensions = new System.Drawing.SizeF (6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size (640, 260); + this.Controls.Add (this.SparkleShareVersion); + this.Controls.Add (this.emptyLabel); + this.Controls.Add (this.copyright); + this.Controls.Add (this.version); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "SparkleAbout"; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "About SparkleShare"; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler (this.SparkleAbout_FormClosing); + this.ResumeLayout (false); + this.PerformLayout (); + + } + + #endregion + + private System.Windows.Forms.Label version; + private System.Windows.Forms.Label copyright; + private System.Windows.Forms.Label emptyLabel; + private System.Windows.Forms.Label SparkleShareVersion; + + + } +} diff --git a/SparkleShare/Windows/SparkleAbout.cs b/SparkleShare/Windows/SparkleAbout.cs new file mode 100644 index 00000000..768b7c97 --- /dev/null +++ b/SparkleShare/Windows/SparkleAbout.cs @@ -0,0 +1,85 @@ +// SparkleShare, a collaboration and sharing tool. +// Copyright (C) 2010 Hylke Bons (hylkebons@gmail.com) +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see (http://www.gnu.org/licenses/). + + +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; + +using System.Windows.Forms; +using System.Drawing; + +namespace SparkleShare { + + public partial class SparkleAbout : Form { + + public SparkleAboutController Controller = new SparkleAboutController (); + + // Short alias for the translations + public static string _(string s) + { + return Program._(s); + } + + + public SparkleAbout () + { + InitializeComponent (); + + this.BackgroundImage=Icons.about; + this.ClientSize = this.BackgroundImage.Size; + this.Icon = Icons.sparkleshare; + + this.SparkleShareVersion.Text = SparkleLib.Defines.VERSION; + this.MaximumSize = this.Size; + this.MinimumSize = this.Size; + this.version.Text = ""; + + Program.TranslateWinForm (this); + + Controller.NewVersionEvent += delegate (string new_version) { + this.version.Invoke((Action)delegate { + this.version.Text = new_version; + }); + }; + + Controller.VersionUpToDateEvent += delegate { + this.version.Invoke((Action)delegate { + this.version.Text = "You are running the latest version."; + }); + }; + + Controller.CheckingForNewVersionEvent += delegate { + this.version.Invoke((Action)delegate { + this.version.Text = "Checking for updates..."; + }); + }; + + } + + private void SparkleAbout_FormClosing (object sender, FormClosingEventArgs e) + { + if (e.CloseReason != CloseReason.ApplicationExitCall + && e.CloseReason != CloseReason.TaskManagerClosing + && e.CloseReason != CloseReason.WindowsShutDown) { + e.Cancel = true; + this.Hide (); + } + } + } +} diff --git a/SparkleShare/Windows/SparkleAbout.resx b/SparkleShare/Windows/SparkleAbout.resx new file mode 100644 index 00000000..53b79502 --- /dev/null +++ b/SparkleShare/Windows/SparkleAbout.resx @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Copyright © 2010-2011 Hylke Bons and others + +SparkleShare is Free and Open Source Software. You are free to use, modify, and redistribute it under the terms of the GNU General Public License version 3 or later. + + \ No newline at end of file diff --git a/SparkleShare/Windows/SparkleBubble.cs b/SparkleShare/Windows/SparkleBubble.cs new file mode 100644 index 00000000..992c6948 --- /dev/null +++ b/SparkleShare/Windows/SparkleBubble.cs @@ -0,0 +1,39 @@ +// SparkleShare, an instant update workflow to Git. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can 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 . + + +using System; +using Notifications; + +namespace SparkleShare { + + public class SparkleBubble : Notification { + + public SparkleBubble (string title, string subtext) : base (title, subtext) + { + System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer (); + timer.Tick += delegate { this.Close (); }; + timer.Interval = 4500; + timer.Start (); + } + + // Checks whether the system allows adding buttons to a notification, + // prevents error messages in Ubuntu. + new public void AddAction (string action, string label, ActionHandler handler) + { + } + } +} diff --git a/SparkleShare/Windows/SparkleBubbles.cs b/SparkleShare/Windows/SparkleBubbles.cs new file mode 100644 index 00000000..c6be2784 --- /dev/null +++ b/SparkleShare/Windows/SparkleBubbles.cs @@ -0,0 +1,36 @@ +// SparkleShare, a collaboration and sharing tool. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can 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 . + + +using System; +using System.Windows.Forms; + +namespace SparkleShare { + + public class SparkleBubbles { + + public SparkleBubblesController Controller = new SparkleBubblesController (); + + + public SparkleBubbles () + { + Controller.ShowBubbleEvent += delegate (string title, string subtext, string image_path) { + SparkleUI.StatusIcon.ShowBalloon(title, subtext, image_path); + }; + } + } +} + diff --git a/SparkleShare/Windows/SparkleController.cs b/SparkleShare/Windows/SparkleController.cs new file mode 100644 index 00000000..9c7a108f --- /dev/null +++ b/SparkleShare/Windows/SparkleController.cs @@ -0,0 +1,235 @@ +// SparkleShare, an instant update workflow to Git. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can 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 . + +using System.Reflection; +using SparkleLib; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Windows.Forms; +using CefSharp; +using Microsoft.Win32; + +namespace SparkleShare { + + public class SparkleController : SparkleControllerBase { + private int sshAgentPid; + + public override string PluginsPath + { + get + { + return Path.Combine (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location), "plugins"); + } + } + + + public SparkleController () : base () + { + } + + public override void Initialize () + { + Settings settings = new Settings (); + BrowserSettings browserSettings = new BrowserSettings (); + + if (!CEF.Initialize (settings, browserSettings)) { + Console.WriteLine ("Couldn't initialise CEF"); + return; + } + + CEF.RegisterScheme ("application", "sparkleshare", new ApplicationSchemeHandlerFactory ()); + CEF.RegisterScheme ("application", "file", new FileSchemeHandlerFactory ()); + + Application.EnableVisualStyles (); + Application.SetCompatibleTextRenderingDefault (false); + + // Add msysgit to path, as we cannot asume it is added to the path + // Asume it is installed in @"\msysgit\bin" + string ExecutableDir = Path.GetDirectoryName(Application.ExecutablePath); + string MSysGit = Path.Combine(ExecutableDir, "msysgit"); + + string newPath = MSysGit + @"\bin" + ";" + + MSysGit + @"\mingw\bin" + ";" + + MSysGit + @"\cmd" + ";" + + System.Environment.ExpandEnvironmentVariables ("%PATH%"); + System.Environment.SetEnvironmentVariable ("PATH", newPath); + System.Environment.SetEnvironmentVariable ("PLINK_PROTOCOL", "ssh"); + + if (String.IsNullOrEmpty (System.Environment.GetEnvironmentVariable ("HOME"))) + System.Environment.SetEnvironmentVariable ("HOME", Environment.ExpandEnvironmentVariables ("%HOMEDRIVE%%HOMEPATH%")); + + StartSshAgent (); + + base.Initialize (); + } + + public override string EventLogHTML + { + get + { + string html = Properties.Resources.event_log_html; + + html = html.Replace ("", "application://sparkleshare/jquery.js"); + + return html; + } + } + + + public override string DayEntryHTML + { + get + { + return Properties.Resources.day_entry_html; + } + } + + + public override string EventEntryHTML + { + get + { + return Properties.Resources.event_entry_html; + } + } + + + // Creates a .desktop entry in autostart folder to + // start SparkleShare automatically at login + public override void CreateStartupItem () + { + } + + + public override void InstallProtocolHandler() + { + // Get assembly location + string location = System.Reflection.Assembly.GetExecutingAssembly().Location; + string folder = Path.GetDirectoryName(location); + string inviteExe = Path.Combine(folder, "SparkleShareInviteOpen.exe"); + + // Register protocol handler as explained in + // http://msdn.microsoft.com/en-us/library/ie/aa767914(v=vs.85).aspx + string mainKey = "HKEY_CLASSES_ROOT\\sparkleshare"; + Registry.SetValue(mainKey, "", "SparkleShare Invites"); + Registry.SetValue(mainKey, "URL Protocol", ""); + + string iconKey = "HKEY_CLASSES_ROOT\\sparkleshare\\DefaultIcon"; + Registry.SetValue(iconKey, "", inviteExe + ",1"); + + string actionKey = "HKEY_CLASSES_ROOT\\sparkleshare\\shell\\open\\command"; + Registry.SetValue(actionKey, "", "\"" + inviteExe + "\" \"%1\""); + } + + + // Adds the SparkleShare folder to the user's + // list of bookmarked places + public override void AddToBookmarks () + { + } + + + // Creates the SparkleShare folder in the user's home folder + public override bool CreateSparkleShareFolder () + { + if (!Directory.Exists(SparkleConfig.DefaultConfig.FoldersPath)) + { + Directory.CreateDirectory(SparkleConfig.DefaultConfig.FoldersPath); + Directory.CreateDirectory(SparkleConfig.DefaultConfig.TmpPath); + SparkleHelpers.DebugInfo("Config", "Created '" + SparkleConfig.DefaultConfig.FoldersPath + "'"); + + return true; + } + + return false; + } + + public override void OpenFile(string url) + { + Process process = new Process(); + process.StartInfo.Arguments = "\"" + url + "\""; + process.StartInfo.FileName = "start"; + + process.Start(); + } + + public override void OpenSparkleShareFolder (string subfolder) + { + Process process = new Process(); + process.StartInfo.Arguments = ",/root," + SparkleHelpers.CombineMore(SparkleConfig.DefaultConfig.FoldersPath, subfolder); + process.StartInfo.FileName = "explorer"; + + process.Start(); + } + + public override void Quit () + { + KillSshAgent (); + base.Quit (); + } + + private void StartSshAgent () + { + if (String.IsNullOrEmpty (System.Environment.GetEnvironmentVariable ("SSH_AUTH_SOCK"))) { + + Process process = new Process (); + process.StartInfo.FileName = "ssh-agent"; + process.StartInfo.UseShellExecute = false; + process.StartInfo.RedirectStandardOutput = true; + + process.Start (); + + string Output = process.StandardOutput.ReadToEnd (); + process.WaitForExit (); + + Match AuthSock = new Regex (@"SSH_AUTH_SOCK=([^;\n\r]*)").Match (Output); + if (AuthSock.Success) { + System.Environment.SetEnvironmentVariable ("SSH_AUTH_SOCK", AuthSock.Groups[1].Value); + } + + Match AgentPid = new Regex (@"SSH_AGENT_PID=([^;\n\r]*)").Match (Output); + if (AgentPid.Success) { + Int32.TryParse (AgentPid.Groups [1].Value, out sshAgentPid); + System.Environment.SetEnvironmentVariable ("SSH_AGENT_PID", AgentPid.Groups[1].Value); + SparkleHelpers.DebugInfo ("SSH", "ssh-agent started, PID=" + AgentPid.Groups[1].Value); + } + else { + SparkleHelpers.DebugInfo ("SSH", "ssh-agent started, PID=unknown"); + } + } + } + + private void KillSshAgent () + { + if (sshAgentPid != 0) { + // Kill the SSH_AGENT that we started + try { + Process.GetProcessById (sshAgentPid).Kill (); + } catch (ArgumentException) { + SparkleHelpers.DebugInfo ("SSH", "Could not kill the ssh-agent, because the process wasn't running"); + } + } + } + + } + +} diff --git a/SparkleShare/Windows/SparkleEventLog.Designer.cs b/SparkleShare/Windows/SparkleEventLog.Designer.cs new file mode 100644 index 00000000..aedf4e7b --- /dev/null +++ b/SparkleShare/Windows/SparkleEventLog.Designer.cs @@ -0,0 +1,89 @@ +namespace SparkleShare { + partial class SparkleEventLog { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + this.WebViewPanel = new System.Windows.Forms.Panel (); + this.panel2 = new System.Windows.Forms.Panel (); + this.combo_box = new System.Windows.Forms.ComboBox (); + this.panel2.SuspendLayout (); + this.SuspendLayout (); + // + // WebViewPanel + // + this.WebViewPanel.Dock = System.Windows.Forms.DockStyle.Fill; + this.WebViewPanel.Location = new System.Drawing.Point (0, 44); + this.WebViewPanel.Name = "WebViewPanel"; + this.WebViewPanel.Size = new System.Drawing.Size (472, 569); + this.WebViewPanel.TabIndex = 1; + // + // panel2 + // + this.panel2.Controls.Add (this.combo_box); + this.panel2.Dock = System.Windows.Forms.DockStyle.Top; + this.panel2.Location = new System.Drawing.Point (0, 0); + this.panel2.Name = "panel2"; + this.panel2.Size = new System.Drawing.Size (472, 44); + this.panel2.TabIndex = 0; + // + // combo_box + // + this.combo_box.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.combo_box.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.combo_box.FormattingEnabled = true; + this.combo_box.Location = new System.Drawing.Point (339, 12); + this.combo_box.Name = "combo_box"; + this.combo_box.Size = new System.Drawing.Size (121, 21); + this.combo_box.TabIndex = 0; + this.combo_box.SelectedIndexChanged += new System.EventHandler (this.combo_box_SelectedIndexChanged); + // + // SparkleEventLog + // + this.AutoScaleDimensions = new System.Drawing.SizeF (6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size (472, 613); + this.Controls.Add (this.WebViewPanel); + this.Controls.Add (this.panel2); + this.Name = "SparkleEventLog"; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Recent Events"; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler (this.SparkleEventLog_FormClosing); + this.panel2.ResumeLayout (false); + this.ResumeLayout (false); + + } + + #endregion + + private System.Windows.Forms.Panel WebViewPanel; + private System.Windows.Forms.Panel panel2; + private System.Windows.Forms.ComboBox combo_box; + + + + + + + } +} diff --git a/SparkleShare/Windows/SparkleEventLog.cs b/SparkleShare/Windows/SparkleEventLog.cs new file mode 100644 index 00000000..2804754e --- /dev/null +++ b/SparkleShare/Windows/SparkleEventLog.cs @@ -0,0 +1,210 @@ +// SparkleShare, a collaboration and sharing tool. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can 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 . + + +using System; +using System.Linq; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text.RegularExpressions; +using System.Threading; + +using System.Windows.Forms; +using System.Drawing; +using System.Runtime.InteropServices; +using System.ComponentModel; + +using SparkleLib; +using CefSharp; +using System.IO; +using System.Text; + +namespace SparkleShare { + + public partial class SparkleEventLog : Form, IBeforeResourceLoad { + private readonly CefWebBrowser _browserControl; + + private string HTML; + private List change_sets; + private string selected_log = null; + + // Short alias for the translations + public static string _ (string s) + { + return Program._ (s); + } + + public SparkleEventLog () + { + InitializeComponent (); + + Program.TranslateWinForm (this); + + this.Icon = Icons.sparkleshare; + + this.change_sets = Program.Controller.GetLog (null); + GenerateHTML (); + + _browserControl = new CefWebBrowser ("application://sparkleshare/eventlog"); + _browserControl.Dock = DockStyle.Fill; + //_browserControl.PropertyChanged += HandleBrowserPropertyChanged; + //_browserControl.ConsoleMessage += HandleConsoleMessage; + _browserControl.BeforeResourceLoadHandler = this; + WebViewPanel.Controls.Add (_browserControl); + + UpdateChooser (); + } + + public void UpdateChooser () + { + this.combo_box.Items.Add (_ ("All Folders")); + this.combo_box.Items.Add (""); + + foreach (string folder_name in Program.Controller.Folders) + this.combo_box.Items.Add (folder_name); + + this.combo_box.SelectedItem = this.combo_box.Items[0]; + } + + + public void UpdateEvents () + { + UpdateEvents (true); + } + + + public void UpdateEvents (bool silent) + { + Thread thread = new Thread (new ThreadStart (delegate { + Program.SetUiCulture (); + Stopwatch watch = new Stopwatch (); + watch.Start (); + this.change_sets = Program.Controller.GetLog (this.selected_log); + GenerateHTML (); + watch.Stop (); + + // A short delay is less annoying than + // a flashing window + if (watch.ElapsedMilliseconds < 500 && !silent) + Thread.Sleep (500 - (int) watch.ElapsedMilliseconds); + + AddHTML (); + })); + + thread.Start (); + } + + + private void GenerateHTML () + { + HTML = Program.Controller.GetHTMLLog (this.change_sets); + + if (HTML == null) + return; + + HTML = HTML.Replace ("", this.Font.Size + "px"); + HTML = HTML.Replace ("", this.Font.Size + "px"); + HTML = HTML.Replace ("", "#0085cf"); + HTML = HTML.Replace ("", "#009ff8"); + HTML = HTML.Replace ("", "\"" + this.Font.FontFamily + "\""); + HTML = HTML.Replace ("", this.ForeColor.ToHex()); + HTML = HTML.Replace ("", this.BackColor.ToHex()); + HTML = HTML.Replace ("", this.BackColor.ToHex()); + HTML = HTML.Replace ("", this.ForeColor.ToHex()); + HTML = HTML.Replace ("", this.ForeColor.ToHex()); + HTML = HTML.Replace ("", + "application://sparkleshare/avatar-default-32.png"); + HTML = HTML.Replace ("", + "application://sparkleshare/document-added-12.png"); + HTML = HTML.Replace ("", + "application://sparkleshare/document-edited-12.png"); + HTML = HTML.Replace ("", + "application://sparkleshare/document-deleted-12.png"); + HTML = HTML.Replace ("", + "application://sparkleshare/document-moved-12.png"); + + HTML = HTML.Replace("href='" + SparkleConfig.DefaultConfig.FoldersPath, "href='application://file/" + SparkleConfig.DefaultConfig.FoldersPath); + HTML = HTML.Replace ("file://application://sparkleshare/", "application://sparkleshare/"); + HTML = HTML.Replace ("file://", "application://file/"); + } + + + private void AddHTML () + { + try + { + Invoke((Action)delegate + { + _browserControl.Reload(); + }); + } + catch (InvalidOperationException e) + { + } + } + + private void SparkleEventLog_FormClosing (object sender, FormClosingEventArgs e) + { + if (e.CloseReason != CloseReason.ApplicationExitCall + && e.CloseReason != CloseReason.TaskManagerClosing + && e.CloseReason != CloseReason.WindowsShutDown) { + e.Cancel = true; + this.Hide (); + } + } + + + #region IBeforeResourceLoad Members + + public void HandleBeforeResourceLoad (CefWebBrowser browserControl, IRequestResponse requestResponse) + { + IRequest request = requestResponse.Request; + Console.WriteLine ("{0} {1}", request.Method, request.Url); + + if (request.Url.StartsWith ("application://sparkleshare/eventlog")) { + Stream resourceStream; + if (HTML != null) + resourceStream = new MemoryStream (Encoding.UTF8.GetPreamble ().Concat (Encoding.UTF8.GetBytes (HTML)).ToArray ()); + else + resourceStream = new MemoryStream (); + + requestResponse.RespondWith (resourceStream, "text/html"); + } else if (request.Url.StartsWith ("application://file/")) { + string Filename = request.Url.Substring ("application://file/".Length); + Filename = Uri.UnescapeDataString (Filename); + Filename = Filename.Replace ("/", "\\"); + + if (Filename.StartsWith(SparkleConfig.DefaultConfig.FoldersPath)) + System.Diagnostics.Process.Start (Filename); + } + } + + #endregion + + private void combo_box_SelectedIndexChanged (object sender, EventArgs e) + { + String SelectedText = this.combo_box.SelectedItem as string; + + if (string.IsNullOrEmpty (SelectedText) || SelectedText.Equals (_ ("All Folders"))) + this.selected_log = null; + else + this.selected_log = SelectedText; + + UpdateEvents (false); + } + } +} + diff --git a/SparkleShare/Windows/SparkleEventLog.resx b/SparkleShare/Windows/SparkleEventLog.resx new file mode 100644 index 00000000..19dc0dd8 --- /dev/null +++ b/SparkleShare/Windows/SparkleEventLog.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SparkleShare/Windows/SparkleSetup.Designer.cs b/SparkleShare/Windows/SparkleSetup.Designer.cs new file mode 100644 index 00000000..a920df7d --- /dev/null +++ b/SparkleShare/Windows/SparkleSetup.Designer.cs @@ -0,0 +1,868 @@ +namespace SparkleShare { + partial class SparkleSetup { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SparkleSetup)); + this.pictureBox = new System.Windows.Forms.PictureBox(); + this.tabControl = new SparkleShare.controls.TablessControl(); + this.setupPage = new System.Windows.Forms.TabPage(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.EmailEntry = new System.Windows.Forms.TextBox(); + this.buttonNext = new System.Windows.Forms.Button(); + this.NameEntry = new System.Windows.Forms.TextBox(); + this.label10 = new System.Windows.Forms.Label(); + this.label13 = new System.Windows.Forms.Label(); + this.label11 = new System.Windows.Forms.Label(); + this.label12 = new System.Windows.Forms.Label(); + this.addPage = new System.Windows.Forms.TabPage(); + this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); + this.label4 = new System.Windows.Forms.Label(); + this.panel_server_selection = new System.Windows.Forms.Panel(); + this.FolderEntry = new SparkleShare.controls.ExampleTextBox(); + this.label14 = new System.Windows.Forms.Label(); + this.ServerEntry = new SparkleShare.controls.ExampleTextBox(); + this.label5 = new System.Windows.Forms.Label(); + this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); + this.buttonSync = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.syncingPage = new System.Windows.Forms.TabPage(); + this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); + this.flowLayoutPanel4 = new System.Windows.Forms.FlowLayoutPanel(); + this.syncFinishButton = new System.Windows.Forms.Button(); + this.syncCancelButton = new System.Windows.Forms.Button(); + this.label6 = new System.Windows.Forms.Label(); + this.syncingProgressBar = new System.Windows.Forms.ProgressBar(); + this.label16 = new System.Windows.Forms.Label(); + this.label15 = new System.Windows.Forms.Label(); + this.errorPage = new System.Windows.Forms.TabPage(); + this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); + this.buttonTryAgain = new System.Windows.Forms.Button(); + this.label2 = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.label1 = new System.Windows.Forms.Label(); + this.finishedPage = new System.Windows.Forms.TabPage(); + this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel(); + this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); + this.buttonOpenFolder = new System.Windows.Forms.Button(); + this.buttonFinished = new System.Windows.Forms.Button(); + this.label9 = new System.Windows.Forms.Label(); + this.label8 = new System.Windows.Forms.Label(); + this.invitePage = new System.Windows.Forms.TabPage(); + this.tableLayoutPanel6 = new System.Windows.Forms.TableLayoutPanel(); + this.flowLayoutPanel3 = new System.Windows.Forms.FlowLayoutPanel(); + this.InviteAddButton = new System.Windows.Forms.Button(); + this.InviteCancelButton = new System.Windows.Forms.Button(); + this.InviteFolderEntry = new System.Windows.Forms.TextBox(); + this.InviteAddressEntry = new System.Windows.Forms.TextBox(); + this.label19 = new System.Windows.Forms.Label(); + this.label18 = new System.Windows.Forms.Label(); + this.label17 = new System.Windows.Forms.Label(); + this.label7 = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); + this.tabControl.SuspendLayout(); + this.setupPage.SuspendLayout(); + this.tableLayoutPanel1.SuspendLayout(); + this.addPage.SuspendLayout(); + this.tableLayoutPanel2.SuspendLayout(); + this.flowLayoutPanel1.SuspendLayout(); + this.syncingPage.SuspendLayout(); + this.tableLayoutPanel3.SuspendLayout(); + this.flowLayoutPanel4.SuspendLayout(); + this.errorPage.SuspendLayout(); + this.tableLayoutPanel4.SuspendLayout(); + this.finishedPage.SuspendLayout(); + this.tableLayoutPanel5.SuspendLayout(); + this.flowLayoutPanel2.SuspendLayout(); + this.invitePage.SuspendLayout(); + this.tableLayoutPanel6.SuspendLayout(); + this.flowLayoutPanel3.SuspendLayout(); + this.SuspendLayout(); + // + // pictureBox + // + this.pictureBox.Dock = System.Windows.Forms.DockStyle.Left; + this.pictureBox.Location = new System.Drawing.Point(0, 0); + this.pictureBox.Name = "pictureBox"; + this.pictureBox.Size = new System.Drawing.Size(150, 396); + this.pictureBox.TabIndex = 1; + this.pictureBox.TabStop = false; + // + // tabControl + // + this.tabControl.Controls.Add(this.setupPage); + this.tabControl.Controls.Add(this.addPage); + this.tabControl.Controls.Add(this.syncingPage); + this.tabControl.Controls.Add(this.errorPage); + this.tabControl.Controls.Add(this.finishedPage); + this.tabControl.Controls.Add(this.invitePage); + this.tabControl.Dock = System.Windows.Forms.DockStyle.Right; + this.tabControl.Location = new System.Drawing.Point(150, 0); + this.tabControl.Name = "tabControl"; + this.tabControl.SelectedIndex = 0; + this.tabControl.Size = new System.Drawing.Size(514, 396); + this.tabControl.TabIndex = 0; + this.tabControl.TabStop = false; + // + // setupPage + // + this.setupPage.Controls.Add(this.tableLayoutPanel1); + this.setupPage.Location = new System.Drawing.Point(4, 22); + this.setupPage.Name = "setupPage"; + this.setupPage.Padding = new System.Windows.Forms.Padding(3); + this.setupPage.Size = new System.Drawing.Size(506, 370); + this.setupPage.TabIndex = 0; + this.setupPage.Text = "Setup"; + this.setupPage.UseVisualStyleBackColor = true; + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 2; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel1.Controls.Add(this.EmailEntry, 1, 4); + this.tableLayoutPanel1.Controls.Add(this.buttonNext, 1, 6); + this.tableLayoutPanel1.Controls.Add(this.NameEntry, 1, 3); + this.tableLayoutPanel1.Controls.Add(this.label10, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.label13, 0, 4); + this.tableLayoutPanel1.Controls.Add(this.label11, 0, 1); + this.tableLayoutPanel1.Controls.Add(this.label12, 0, 3); + this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 3); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(5); + this.tableLayoutPanel1.RowCount = 7; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 30F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 70F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(500, 364); + this.tableLayoutPanel1.TabIndex = 8; + // + // EmailEntry + // + this.EmailEntry.Dock = System.Windows.Forms.DockStyle.Fill; + this.EmailEntry.Location = new System.Drawing.Point(81, 153); + this.EmailEntry.Name = "EmailEntry"; + this.EmailEntry.Size = new System.Drawing.Size(411, 20); + this.EmailEntry.TabIndex = 10; + this.EmailEntry.TextChanged += new System.EventHandler(this.CheckSetupPage); + // + // buttonNext + // + this.buttonNext.Dock = System.Windows.Forms.DockStyle.Right; + this.buttonNext.Enabled = false; + this.buttonNext.Location = new System.Drawing.Point(417, 331); + this.buttonNext.Name = "buttonNext"; + this.buttonNext.Size = new System.Drawing.Size(75, 25); + this.buttonNext.TabIndex = 3; + this.buttonNext.Text = "Continue"; + this.buttonNext.UseVisualStyleBackColor = true; + this.buttonNext.Click += new System.EventHandler(this.SetupNextClicked); + // + // NameEntry + // + this.NameEntry.Dock = System.Windows.Forms.DockStyle.Fill; + this.NameEntry.Location = new System.Drawing.Point(81, 128); + this.NameEntry.Name = "NameEntry"; + this.NameEntry.Size = new System.Drawing.Size(411, 20); + this.NameEntry.TabIndex = 9; + this.NameEntry.TextChanged += new System.EventHandler(this.CheckSetupPage); + // + // label10 + // + this.label10.AutoSize = true; + this.tableLayoutPanel1.SetColumnSpan(this.label10, 2); + this.label10.Dock = System.Windows.Forms.DockStyle.Fill; + this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label10.Location = new System.Drawing.Point(8, 5); + this.label10.Name = "label10"; + this.label10.Size = new System.Drawing.Size(484, 25); + this.label10.TabIndex = 1; + this.label10.Text = "Welcome to SparkleShare!"; + // + // label13 + // + this.label13.AutoSize = true; + this.label13.Dock = System.Windows.Forms.DockStyle.Fill; + this.label13.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label13.Location = new System.Drawing.Point(8, 150); + this.label13.Name = "label13"; + this.label13.Size = new System.Drawing.Size(67, 25); + this.label13.TabIndex = 8; + this.label13.Text = "Email:"; + this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // label11 + // + this.tableLayoutPanel1.SetColumnSpan(this.label11, 2); + this.label11.Dock = System.Windows.Forms.DockStyle.Fill; + this.label11.Location = new System.Drawing.Point(8, 30); + this.label11.Name = "label11"; + this.label11.Size = new System.Drawing.Size(484, 30); + this.label11.TabIndex = 2; + this.label11.Text = "Before we get started, what\'s your name and email?\r\nDon\'t worry, this information" + + " is only visible to your team members."; + // + // label12 + // + this.label12.AutoSize = true; + this.label12.Dock = System.Windows.Forms.DockStyle.Fill; + this.label12.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label12.Location = new System.Drawing.Point(8, 125); + this.label12.Name = "label12"; + this.label12.Size = new System.Drawing.Size(67, 25); + this.label12.TabIndex = 7; + this.label12.Text = "Full Name:"; + this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // addPage + // + this.addPage.Controls.Add(this.tableLayoutPanel2); + this.addPage.Location = new System.Drawing.Point(4, 22); + this.addPage.Name = "addPage"; + this.addPage.Padding = new System.Windows.Forms.Padding(3); + this.addPage.Size = new System.Drawing.Size(506, 370); + this.addPage.TabIndex = 1; + this.addPage.Text = "Add"; + this.addPage.UseVisualStyleBackColor = true; + // + // tableLayoutPanel2 + // + this.tableLayoutPanel2.ColumnCount = 2; + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel2.Controls.Add(this.label4, 0, 0); + this.tableLayoutPanel2.Controls.Add(this.panel_server_selection, 0, 2); + this.tableLayoutPanel2.Controls.Add(this.FolderEntry, 1, 5); + this.tableLayoutPanel2.Controls.Add(this.label14, 0, 4); + this.tableLayoutPanel2.Controls.Add(this.ServerEntry, 0, 5); + this.tableLayoutPanel2.Controls.Add(this.label5, 1, 4); + this.tableLayoutPanel2.Controls.Add(this.flowLayoutPanel1, 1, 7); + this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 3); + this.tableLayoutPanel2.Name = "tableLayoutPanel2"; + this.tableLayoutPanel2.Padding = new System.Windows.Forms.Padding(10); + this.tableLayoutPanel2.RowCount = 8; + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 32F)); + this.tableLayoutPanel2.Size = new System.Drawing.Size(500, 364); + this.tableLayoutPanel2.TabIndex = 18; + // + // label4 + // + this.label4.AutoSize = true; + this.tableLayoutPanel2.SetColumnSpan(this.label4, 2); + this.label4.Dock = System.Windows.Forms.DockStyle.Fill; + this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label4.Location = new System.Drawing.Point(13, 10); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(474, 30); + this.label4.TabIndex = 0; + this.label4.Text = "Where\'s your project hosted?"; + // + // panel_server_selection + // + this.tableLayoutPanel2.SetColumnSpan(this.panel_server_selection, 2); + this.panel_server_selection.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel_server_selection.Location = new System.Drawing.Point(13, 63); + this.panel_server_selection.Name = "panel_server_selection"; + this.panel_server_selection.Size = new System.Drawing.Size(474, 171); + this.panel_server_selection.TabIndex = 12; + // + // FolderEntry + // + this.FolderEntry.Dock = System.Windows.Forms.DockStyle.Fill; + this.FolderEntry.ExampleText = ""; + this.FolderEntry.ForeColor = System.Drawing.SystemColors.InactiveCaptionText; + this.FolderEntry.Location = new System.Drawing.Point(253, 280); + this.FolderEntry.Name = "FolderEntry"; + this.FolderEntry.Size = new System.Drawing.Size(234, 20); + this.FolderEntry.TabIndex = 17; + this.FolderEntry.TextChanged += new System.EventHandler(this.CheckAddPage); + // + // label14 + // + this.label14.AutoSize = true; + this.label14.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label14.Location = new System.Drawing.Point(13, 257); + this.label14.Name = "label14"; + this.label14.Size = new System.Drawing.Size(67, 17); + this.label14.TabIndex = 14; + this.label14.Text = "Address"; + // + // ServerEntry + // + this.ServerEntry.Dock = System.Windows.Forms.DockStyle.Fill; + this.ServerEntry.ExampleText = ""; + this.ServerEntry.ForeColor = System.Drawing.SystemColors.InactiveCaptionText; + this.ServerEntry.Location = new System.Drawing.Point(13, 280); + this.ServerEntry.Name = "ServerEntry"; + this.ServerEntry.Size = new System.Drawing.Size(234, 20); + this.ServerEntry.TabIndex = 16; + this.ServerEntry.TextChanged += new System.EventHandler(this.CheckAddPage); + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label5.Location = new System.Drawing.Point(253, 257); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(101, 17); + this.label5.TabIndex = 15; + this.label5.Text = "Remote Path"; + // + // flowLayoutPanel1 + // + this.flowLayoutPanel1.Controls.Add(this.buttonSync); + this.flowLayoutPanel1.Controls.Add(this.buttonCancel); + this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Right; + this.flowLayoutPanel1.Location = new System.Drawing.Point(328, 322); + this.flowLayoutPanel1.Margin = new System.Windows.Forms.Padding(0); + this.flowLayoutPanel1.Name = "flowLayoutPanel1"; + this.flowLayoutPanel1.Size = new System.Drawing.Size(162, 32); + this.flowLayoutPanel1.TabIndex = 18; + // + // buttonSync + // + this.buttonSync.Enabled = false; + this.buttonSync.Location = new System.Drawing.Point(3, 3); + this.buttonSync.Name = "buttonSync"; + this.buttonSync.Size = new System.Drawing.Size(75, 25); + this.buttonSync.TabIndex = 9; + this.buttonSync.Text = "Add"; + this.buttonSync.UseVisualStyleBackColor = true; + this.buttonSync.Click += new System.EventHandler(this.AddButtonClicked); + // + // buttonCancel + // + this.buttonCancel.Dock = System.Windows.Forms.DockStyle.Right; + this.buttonCancel.Location = new System.Drawing.Point(84, 3); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 25); + this.buttonCancel.TabIndex = 8; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.CancelButtonClicked); + // + // syncingPage + // + this.syncingPage.Controls.Add(this.tableLayoutPanel3); + this.syncingPage.Location = new System.Drawing.Point(4, 22); + this.syncingPage.Name = "syncingPage"; + this.syncingPage.Size = new System.Drawing.Size(506, 370); + this.syncingPage.TabIndex = 2; + this.syncingPage.Text = "Syncing"; + this.syncingPage.UseVisualStyleBackColor = true; + // + // tableLayoutPanel3 + // + this.tableLayoutPanel3.ColumnCount = 1; + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel3.Controls.Add(this.flowLayoutPanel4, 0, 6); + this.tableLayoutPanel3.Controls.Add(this.label6, 0, 0); + this.tableLayoutPanel3.Controls.Add(this.syncingProgressBar, 0, 4); + this.tableLayoutPanel3.Controls.Add(this.label16, 0, 2); + this.tableLayoutPanel3.Controls.Add(this.label15, 0, 1); + this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel3.Location = new System.Drawing.Point(0, 0); + this.tableLayoutPanel3.Name = "tableLayoutPanel3"; + this.tableLayoutPanel3.Padding = new System.Windows.Forms.Padding(10); + this.tableLayoutPanel3.RowCount = 7; + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 15F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 15F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); + this.tableLayoutPanel3.Size = new System.Drawing.Size(506, 370); + this.tableLayoutPanel3.TabIndex = 6; + // + // flowLayoutPanel4 + // + this.flowLayoutPanel4.Controls.Add(this.syncFinishButton); + this.flowLayoutPanel4.Controls.Add(this.syncCancelButton); + this.flowLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Right; + this.flowLayoutPanel4.Location = new System.Drawing.Point(334, 330); + this.flowLayoutPanel4.Margin = new System.Windows.Forms.Padding(0); + this.flowLayoutPanel4.Name = "flowLayoutPanel4"; + this.flowLayoutPanel4.Size = new System.Drawing.Size(162, 30); + this.flowLayoutPanel4.TabIndex = 19; + // + // syncFinishButton + // + this.syncFinishButton.Enabled = false; + this.syncFinishButton.Location = new System.Drawing.Point(3, 3); + this.syncFinishButton.Name = "syncFinishButton"; + this.syncFinishButton.Size = new System.Drawing.Size(75, 25); + this.syncFinishButton.TabIndex = 9; + this.syncFinishButton.Text = "Finish"; + this.syncFinishButton.UseVisualStyleBackColor = true; + // + // syncCancelButton + // + this.syncCancelButton.Dock = System.Windows.Forms.DockStyle.Right; + this.syncCancelButton.Location = new System.Drawing.Point(84, 3); + this.syncCancelButton.Name = "syncCancelButton"; + this.syncCancelButton.Size = new System.Drawing.Size(75, 25); + this.syncCancelButton.TabIndex = 8; + this.syncCancelButton.Text = "Cancel"; + this.syncCancelButton.UseVisualStyleBackColor = true; + this.syncCancelButton.Click += new System.EventHandler(this.syncCancelClicked); + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Dock = System.Windows.Forms.DockStyle.Fill; + this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); + this.label6.Location = new System.Drawing.Point(13, 10); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(480, 25); + this.label6.TabIndex = 0; + this.label6.Text = "Syncing…"; + // + // syncingProgressBar + // + this.syncingProgressBar.Location = new System.Drawing.Point(13, 115); + this.syncingProgressBar.Name = "syncingProgressBar"; + this.syncingProgressBar.Size = new System.Drawing.Size(480, 23); + this.syncingProgressBar.TabIndex = 3; + // + // label16 + // + this.label16.AutoSize = true; + this.label16.Dock = System.Windows.Forms.DockStyle.Fill; + this.label16.Location = new System.Drawing.Point(13, 50); + this.label16.Name = "label16"; + this.label16.Size = new System.Drawing.Size(480, 15); + this.label16.TabIndex = 5; + this.label16.Text = "Are you sure it’s not coffee o\'clock?"; + // + // label15 + // + this.label15.AutoSize = true; + this.label15.Dock = System.Windows.Forms.DockStyle.Fill; + this.label15.Location = new System.Drawing.Point(13, 35); + this.label15.Name = "label15"; + this.label15.Size = new System.Drawing.Size(480, 15); + this.label15.TabIndex = 4; + this.label15.Text = "This may take a while."; + // + // errorPage + // + this.errorPage.Controls.Add(this.tableLayoutPanel4); + this.errorPage.Location = new System.Drawing.Point(4, 22); + this.errorPage.Name = "errorPage"; + this.errorPage.Size = new System.Drawing.Size(506, 370); + this.errorPage.TabIndex = 3; + this.errorPage.Text = "Error"; + this.errorPage.UseVisualStyleBackColor = true; + // + // tableLayoutPanel4 + // + this.tableLayoutPanel4.ColumnCount = 1; + this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel4.Controls.Add(this.buttonTryAgain, 0, 5); + this.tableLayoutPanel4.Controls.Add(this.label2, 0, 1); + this.tableLayoutPanel4.Controls.Add(this.label3, 0, 3); + this.tableLayoutPanel4.Controls.Add(this.label1, 0, 0); + this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel4.Location = new System.Drawing.Point(0, 0); + this.tableLayoutPanel4.Name = "tableLayoutPanel4"; + this.tableLayoutPanel4.Padding = new System.Windows.Forms.Padding(10); + this.tableLayoutPanel4.RowCount = 6; + this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F)); + this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 70F)); + this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F)); + this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); + this.tableLayoutPanel4.Size = new System.Drawing.Size(506, 370); + this.tableLayoutPanel4.TabIndex = 4; + // + // buttonTryAgain + // + this.buttonTryAgain.Dock = System.Windows.Forms.DockStyle.Right; + this.buttonTryAgain.Location = new System.Drawing.Point(418, 333); + this.buttonTryAgain.Name = "buttonTryAgain"; + this.buttonTryAgain.Size = new System.Drawing.Size(75, 24); + this.buttonTryAgain.TabIndex = 3; + this.buttonTryAgain.Text = "Try Again…"; + this.buttonTryAgain.UseVisualStyleBackColor = true; + this.buttonTryAgain.Click += new System.EventHandler(this.buttonTryAgain_Click); + // + // label2 + // + this.label2.Dock = System.Windows.Forms.DockStyle.Fill; + this.label2.Location = new System.Drawing.Point(13, 30); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(480, 40); + this.label2.TabIndex = 1; + this.label2.Text = "We don\'t know exactly what the problem is, but we can try to help you pinpoint it" + + "."; + this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // label3 + // + this.label3.Dock = System.Windows.Forms.DockStyle.Fill; + this.label3.Location = new System.Drawing.Point(13, 108); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(480, 70); + this.label3.TabIndex = 2; + this.label3.Text = resources.GetString("label3.Text"); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Dock = System.Windows.Forms.DockStyle.Fill; + this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); + this.label1.Location = new System.Drawing.Point(13, 10); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(480, 20); + this.label1.TabIndex = 0; + this.label1.Text = "Something went wrong"; + // + // finishedPage + // + this.finishedPage.Controls.Add(this.tableLayoutPanel5); + this.finishedPage.Location = new System.Drawing.Point(4, 22); + this.finishedPage.Name = "finishedPage"; + this.finishedPage.Size = new System.Drawing.Size(506, 370); + this.finishedPage.TabIndex = 4; + this.finishedPage.Text = "Finished"; + this.finishedPage.UseVisualStyleBackColor = true; + // + // tableLayoutPanel5 + // + this.tableLayoutPanel5.ColumnCount = 1; + this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel5.Controls.Add(this.flowLayoutPanel2, 0, 3); + this.tableLayoutPanel5.Controls.Add(this.label9, 0, 1); + this.tableLayoutPanel5.Controls.Add(this.label8, 0, 0); + this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel5.Location = new System.Drawing.Point(0, 0); + this.tableLayoutPanel5.Name = "tableLayoutPanel5"; + this.tableLayoutPanel5.Padding = new System.Windows.Forms.Padding(10); + this.tableLayoutPanel5.RowCount = 4; + this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); + this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 15F)); + this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); + this.tableLayoutPanel5.Size = new System.Drawing.Size(506, 370); + this.tableLayoutPanel5.TabIndex = 4; + // + // flowLayoutPanel2 + // + this.flowLayoutPanel2.Controls.Add(this.buttonOpenFolder); + this.flowLayoutPanel2.Controls.Add(this.buttonFinished); + this.flowLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Right; + this.flowLayoutPanel2.Location = new System.Drawing.Point(334, 330); + this.flowLayoutPanel2.Margin = new System.Windows.Forms.Padding(0); + this.flowLayoutPanel2.Name = "flowLayoutPanel2"; + this.flowLayoutPanel2.Size = new System.Drawing.Size(162, 30); + this.flowLayoutPanel2.TabIndex = 0; + // + // buttonOpenFolder + // + this.buttonOpenFolder.Location = new System.Drawing.Point(3, 3); + this.buttonOpenFolder.Name = "buttonOpenFolder"; + this.buttonOpenFolder.Size = new System.Drawing.Size(75, 23); + this.buttonOpenFolder.TabIndex = 0; + this.buttonOpenFolder.Text = "Open Folder"; + this.buttonOpenFolder.UseVisualStyleBackColor = true; + this.buttonOpenFolder.Click += new System.EventHandler(this.buttonOpenFolder_Click); + // + // buttonFinished + // + this.buttonFinished.Location = new System.Drawing.Point(84, 3); + this.buttonFinished.Name = "buttonFinished"; + this.buttonFinished.Size = new System.Drawing.Size(75, 23); + this.buttonFinished.TabIndex = 1; + this.buttonFinished.Text = "Finish"; + this.buttonFinished.UseVisualStyleBackColor = true; + this.buttonFinished.Click += new System.EventHandler(this.buttonFinished_Click); + // + // label9 + // + this.label9.Location = new System.Drawing.Point(13, 35); + this.label9.Name = "label9"; + this.label9.Size = new System.Drawing.Size(307, 15); + this.label9.TabIndex = 3; + this.label9.Text = "Access the files from your SparkleShare folder."; + // + // label8 + // + this.label8.AutoSize = true; + this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); + this.label8.Location = new System.Drawing.Point(13, 10); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(227, 20); + this.label8.TabIndex = 2; + this.label8.Text = "Project successfully added!"; + // + // invitePage + // + this.invitePage.Controls.Add(this.tableLayoutPanel6); + this.invitePage.Location = new System.Drawing.Point(4, 22); + this.invitePage.Name = "invitePage"; + this.invitePage.Padding = new System.Windows.Forms.Padding(3); + this.invitePage.Size = new System.Drawing.Size(506, 370); + this.invitePage.TabIndex = 5; + this.invitePage.Text = "Invite"; + this.invitePage.UseVisualStyleBackColor = true; + // + // tableLayoutPanel6 + // + this.tableLayoutPanel6.ColumnCount = 2; + this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel6.Controls.Add(this.flowLayoutPanel3, 1, 6); + this.tableLayoutPanel6.Controls.Add(this.InviteFolderEntry, 1, 4); + this.tableLayoutPanel6.Controls.Add(this.InviteAddressEntry, 1, 3); + this.tableLayoutPanel6.Controls.Add(this.label19, 0, 4); + this.tableLayoutPanel6.Controls.Add(this.label18, 0, 3); + this.tableLayoutPanel6.Controls.Add(this.label17, 0, 1); + this.tableLayoutPanel6.Controls.Add(this.label7, 0, 0); + this.tableLayoutPanel6.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel6.Location = new System.Drawing.Point(3, 3); + this.tableLayoutPanel6.Name = "tableLayoutPanel6"; + this.tableLayoutPanel6.RowCount = 7; + this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); + this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 30F)); + this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); + this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); + this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 70F)); + this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 32F)); + this.tableLayoutPanel6.Size = new System.Drawing.Size(500, 364); + this.tableLayoutPanel6.TabIndex = 0; + // + // flowLayoutPanel3 + // + this.flowLayoutPanel3.Controls.Add(this.InviteAddButton); + this.flowLayoutPanel3.Controls.Add(this.InviteCancelButton); + this.flowLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Right; + this.flowLayoutPanel3.Location = new System.Drawing.Point(338, 331); + this.flowLayoutPanel3.Margin = new System.Windows.Forms.Padding(0); + this.flowLayoutPanel3.Name = "flowLayoutPanel3"; + this.flowLayoutPanel3.Size = new System.Drawing.Size(162, 33); + this.flowLayoutPanel3.TabIndex = 19; + // + // InviteAddButton + // + this.InviteAddButton.Enabled = false; + this.InviteAddButton.Location = new System.Drawing.Point(3, 3); + this.InviteAddButton.Name = "InviteAddButton"; + this.InviteAddButton.Size = new System.Drawing.Size(75, 25); + this.InviteAddButton.TabIndex = 9; + this.InviteAddButton.Text = "Add"; + this.InviteAddButton.UseVisualStyleBackColor = true; + this.InviteAddButton.Click += new System.EventHandler(this.InviteAddButtonClicked); + // + // InviteCancelButton + // + this.InviteCancelButton.Dock = System.Windows.Forms.DockStyle.Right; + this.InviteCancelButton.Location = new System.Drawing.Point(84, 3); + this.InviteCancelButton.Name = "InviteCancelButton"; + this.InviteCancelButton.Size = new System.Drawing.Size(75, 25); + this.InviteCancelButton.TabIndex = 8; + this.InviteCancelButton.Text = "Cancel"; + this.InviteCancelButton.UseVisualStyleBackColor = true; + this.InviteCancelButton.Click += new System.EventHandler(this.InviteCancelButtonClicked); + // + // InviteFolderEntry + // + this.InviteFolderEntry.Dock = System.Windows.Forms.DockStyle.Fill; + this.InviteFolderEntry.Location = new System.Drawing.Point(93, 144); + this.InviteFolderEntry.Name = "InviteFolderEntry"; + this.InviteFolderEntry.ReadOnly = true; + this.InviteFolderEntry.Size = new System.Drawing.Size(404, 20); + this.InviteFolderEntry.TabIndex = 11; + // + // InviteAddressEntry + // + this.InviteAddressEntry.Dock = System.Windows.Forms.DockStyle.Fill; + this.InviteAddressEntry.Location = new System.Drawing.Point(93, 119); + this.InviteAddressEntry.Name = "InviteAddressEntry"; + this.InviteAddressEntry.ReadOnly = true; + this.InviteAddressEntry.Size = new System.Drawing.Size(404, 20); + this.InviteAddressEntry.TabIndex = 10; + // + // label19 + // + this.label19.AutoSize = true; + this.label19.Dock = System.Windows.Forms.DockStyle.Fill; + this.label19.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label19.Location = new System.Drawing.Point(3, 141); + this.label19.Name = "label19"; + this.label19.Size = new System.Drawing.Size(84, 25); + this.label19.TabIndex = 9; + this.label19.Text = "Remote Path:"; + this.label19.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // label18 + // + this.label18.AutoSize = true; + this.label18.Dock = System.Windows.Forms.DockStyle.Fill; + this.label18.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label18.Location = new System.Drawing.Point(3, 116); + this.label18.Name = "label18"; + this.label18.Size = new System.Drawing.Size(84, 25); + this.label18.TabIndex = 8; + this.label18.Text = "Address:"; + this.label18.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // label17 + // + this.tableLayoutPanel6.SetColumnSpan(this.label17, 2); + this.label17.Dock = System.Windows.Forms.DockStyle.Fill; + this.label17.Location = new System.Drawing.Point(3, 25); + this.label17.Name = "label17"; + this.label17.Size = new System.Drawing.Size(494, 20); + this.label17.TabIndex = 3; + this.label17.Text = "Do you want to add this project to SparkleShare?"; + // + // label7 + // + this.label7.AutoSize = true; + this.tableLayoutPanel6.SetColumnSpan(this.label7, 2); + this.label7.Dock = System.Windows.Forms.DockStyle.Fill; + this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label7.Location = new System.Drawing.Point(3, 0); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(494, 25); + this.label7.TabIndex = 2; + this.label7.Text = "You\'ve received an invite!"; + // + // SparkleSetup + // + this.ClientSize = new System.Drawing.Size(664, 396); + this.Controls.Add(this.tabControl); + this.Controls.Add(this.pictureBox); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.MaximizeBox = false; + this.Name = "SparkleSetup"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "SparkleShare Setup"; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SparkleSetup_FormClosing); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); + this.tabControl.ResumeLayout(false); + this.setupPage.ResumeLayout(false); + this.tableLayoutPanel1.ResumeLayout(false); + this.tableLayoutPanel1.PerformLayout(); + this.addPage.ResumeLayout(false); + this.tableLayoutPanel2.ResumeLayout(false); + this.tableLayoutPanel2.PerformLayout(); + this.flowLayoutPanel1.ResumeLayout(false); + this.syncingPage.ResumeLayout(false); + this.tableLayoutPanel3.ResumeLayout(false); + this.tableLayoutPanel3.PerformLayout(); + this.flowLayoutPanel4.ResumeLayout(false); + this.errorPage.ResumeLayout(false); + this.tableLayoutPanel4.ResumeLayout(false); + this.tableLayoutPanel4.PerformLayout(); + this.finishedPage.ResumeLayout(false); + this.tableLayoutPanel5.ResumeLayout(false); + this.tableLayoutPanel5.PerformLayout(); + this.flowLayoutPanel2.ResumeLayout(false); + this.invitePage.ResumeLayout(false); + this.tableLayoutPanel6.ResumeLayout(false); + this.tableLayoutPanel6.PerformLayout(); + this.flowLayoutPanel3.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private SparkleShare.controls.TablessControl tabControl; + private System.Windows.Forms.TabPage setupPage; + private System.Windows.Forms.TabPage addPage; + private System.Windows.Forms.TabPage syncingPage; + private System.Windows.Forms.TabPage errorPage; + private System.Windows.Forms.TabPage finishedPage; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.Button buttonSync; + private System.Windows.Forms.Button buttonCancel; + private System.Windows.Forms.PictureBox pictureBox; + private System.Windows.Forms.Label label6; + private System.Windows.Forms.ProgressBar syncingProgressBar; + private System.Windows.Forms.Button buttonTryAgain; + private System.Windows.Forms.Label label9; + private System.Windows.Forms.Label label8; + private System.Windows.Forms.Button buttonFinished; + private System.Windows.Forms.Button buttonOpenFolder; + private System.Windows.Forms.Label label11; + private System.Windows.Forms.Label label10; + private System.Windows.Forms.Panel panel_server_selection; + private System.Windows.Forms.TextBox EmailEntry; + private System.Windows.Forms.TextBox NameEntry; + private System.Windows.Forms.Label label13; + private System.Windows.Forms.Label label12; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.Label label14; + private SparkleShare.controls.ExampleTextBox FolderEntry; + private SparkleShare.controls.ExampleTextBox ServerEntry; + private System.Windows.Forms.Label label16; + private System.Windows.Forms.Label label15; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.Button buttonNext; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; + private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5; + private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2; + private System.Windows.Forms.TabPage invitePage; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel6; + private System.Windows.Forms.Label label17; + private System.Windows.Forms.Label label7; + private System.Windows.Forms.Label label19; + private System.Windows.Forms.Label label18; + private System.Windows.Forms.TextBox InviteFolderEntry; + private System.Windows.Forms.TextBox InviteAddressEntry; + private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel3; + private System.Windows.Forms.Button InviteAddButton; + private System.Windows.Forms.Button InviteCancelButton; + private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel4; + private System.Windows.Forms.Button syncFinishButton; + private System.Windows.Forms.Button syncCancelButton; + + + + + } +} diff --git a/SparkleShare/Windows/SparkleSetup.cs b/SparkleShare/Windows/SparkleSetup.cs new file mode 100644 index 00000000..f85c0d5e --- /dev/null +++ b/SparkleShare/Windows/SparkleSetup.cs @@ -0,0 +1,294 @@ +// SparkleShare, a collaboration and sharing tool. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General private 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 private License for more details. +// +// You should have received a copy of the GNU General private License +// along with this program. If not, see . + + +using System; +using System.Diagnostics; +using System.IO; +using System.Text.RegularExpressions; +using System.Timers; +using System.Collections.Generic; +using System.Threading; + +using System.Windows.Forms; +using System.Drawing; + + +namespace SparkleShare { + + public partial class SparkleSetup : Form { + + public SparkleSetupController Controller = new SparkleSetupController (); + + private TreeView treeView; + + // Short alias for the translations + public static string _ (string s) { + return Program._ (s); + } + + + public SparkleSetup () { + InitializeComponent (); + + Program.TranslateWinForm (this); + + pictureBox.Image = Icons.side_splash; + this.Icon = Icons.sparkleshare; + + Controller.HideWindowEvent += delegate + { + this.Hide(); + }; + + Controller.ShowWindowEvent += delegate + { + this.Show(); + }; + + Controller.ChangePageEvent += delegate (PageType type, string [] warnings) { + tabControl.SafeInvoke ((Action)delegate { + switch (type) { + case PageType.Setup: + tabControl.SelectedIndex = 0; + NameEntry.Text = Controller.GuessedUserName; + EmailEntry.Text = Controller.GuessedUserEmail; + Show(); + Controller.CheckSetupPage(NameEntry.Text, EmailEntry.Text); + break; + + case PageType.Add: + tabControl.SelectedIndex = 1; + + // Add plugins to tree + // =================== + // Check whether the treeView is already created + // If it is dispose it and start over + if (treeView != null) { + treeView.Dispose(); + } + // Set up the treeview + ImageList imageList = new ImageList (); + imageList.ImageSize = new Size (24, 24); + treeView = new TreeView (); + treeView.DrawMode = System.Windows.Forms.TreeViewDrawMode.OwnerDrawText; + treeView.FullRowSelect = true; + treeView.ImageIndex = 0; + treeView.Indent = 35; + treeView.HideSelection = false; + treeView.ItemHeight = 40; + + TreeNode [] nodes = new TreeNode [Controller.Plugins.Count]; + + for (int i = 0; i < Controller.Plugins.Count; i++) { + nodes [i] = new TreeNode (Controller.Plugins [i].Name + ";" + Controller.Plugins [i].Description); + nodes [i].ImageIndex = i; + nodes [i].SelectedImageIndex = i; + nodes [i].Tag = Controller.Plugins [i].Name; + imageList.Images.Add (Image.FromFile (Controller.Plugins [i].ImagePath)); + } + + treeView.Nodes.AddRange (nodes); + treeView.ImageList = imageList; + treeView.ShowLines = false; + treeView.ShowRootLines = false; + treeView.Size = new System.Drawing.Size (panel_server_selection.Size.Width, + panel_server_selection.Size.Height); + + panel_server_selection.Controls.Add (treeView); + // Finished adding and populating tree + + // Select first node + treeView.SelectedNode = treeView.Nodes[0]; + treeView.Select(); + Controller.SelectedPluginChanged(0); + + treeView.AfterSelect += new TreeViewEventHandler(CheckTreeNode); + + Show (); + Controller.CheckAddPage(ServerEntry.Text, FolderEntry.Text, 1); + break; + + case PageType.Invite: + tabControl.SelectedIndex = 5; + InviteAddressEntry.Text = Controller.PendingInvite.Address; + InviteFolderEntry.Text = Controller.PendingInvite.RemotePath; + Show(); + break; + + case PageType.Syncing: + tabControl.SelectedIndex = 2; + Show(); + break; + + case PageType.Error: + tabControl.SelectedIndex = 3; + label3.Text = "First, have you tried turning it off and on again?\n\n" + + Controller.PreviousUrl + " is the address we've compiled. Does this look alright?\n\n" + + "The host needs to know who you are. Have you uploaded the key that sits in your SparkleShare folder?"; + Show (); + break; + + case PageType.Finished: + tabControl.SelectedIndex = 4; + Show (); + break; + + case PageType.Tutorial: + // Do nothing in tutorial by now + Controller.TutorialSkipped();; + break; + + default: + throw new NotImplementedException ("unknown PageType"); + } + }); + }; + + Controller.UpdateSetupContinueButtonEvent += new SparkleSetupController.UpdateSetupContinueButtonEventHandler(UpdateSetupContinueButtonEvent); + + Controller.ChangeAddressFieldEvent += new SparkleSetupController.ChangeAddressFieldEventHandler(ChangeAddressFieldEvent); + Controller.ChangePathFieldEvent += new SparkleSetupController.ChangePathFieldEventHandler(ChangePathFieldEvent); + Controller.UpdateAddProjectButtonEvent += new SparkleSetupController.UpdateAddProjectButtonEventHandler(UpdateAddProjectButtonEvent); + + Controller.UpdateProgressBarEvent += new SparkleSetupController.UpdateProgressBarEventHandler(UpdateProgressBarEvent); + } + + private void SparkleSetup_FormClosing (object sender, FormClosingEventArgs e) { + if (e.CloseReason != CloseReason.ApplicationExitCall + && e.CloseReason != CloseReason.TaskManagerClosing + && e.CloseReason != CloseReason.WindowsShutDown) { + e.Cancel = true; + this.Hide (); + } + } + + #region Things for "Setup" page + private void SetupNextClicked(object sender, EventArgs e) + { + Controller.SetupPageCompleted(NameEntry.Text, EmailEntry.Text); + } + + private void CheckSetupPage(object sender, EventArgs e) + { + Controller.CheckSetupPage(NameEntry.Text, EmailEntry.Text); + } + + void UpdateSetupContinueButtonEvent(bool button_enabled) + { + buttonNext.Enabled = button_enabled; + } + #endregion + + #region Things for "Add" page + void ChangeAddressFieldEvent(string text, string example_text, FieldState state) + { + ServerEntry.Text = text; + ServerEntry.Enabled = state == FieldState.Enabled; + ServerEntry.ExampleText = example_text; + } + + void ChangePathFieldEvent(string text, string example_text, FieldState state) + { + FolderEntry.Text = text; + FolderEntry.Enabled = state == FieldState.Enabled; + FolderEntry.ExampleText = example_text; + } + + private void CheckTreeNode(object sender, EventArgs e) + { + Controller.SelectedPluginChanged(treeView.SelectedNode.Index); + } + + private void CancelButtonClicked (object sender, EventArgs e) { + Controller.PageCancelled(); + } + + private void AddButtonClicked(object sender, EventArgs e) + { + Controller.AddPageCompleted(ServerEntry.Text, FolderEntry.Text); + } + + void UpdateAddProjectButtonEvent(bool button_enabled) + { + buttonSync.Enabled = button_enabled; + } + + private void CheckAddPage(object sender, EventArgs e) + { + Controller.CheckAddPage(ServerEntry.Text, FolderEntry.Text, treeView.SelectedNode.Index); + } + #endregion + + #region Things for "Invite" page + private void InviteAddButtonClicked(object sender, EventArgs e) + { + Controller.InvitePageCompleted(); + } + + private void InviteCancelButtonClicked(object sender, EventArgs e) + { + Controller.PageCancelled(); + } + #endregion + + #region Things for "Syncing" page + private void syncCancelClicked(object sender, EventArgs e) + { + Controller.SyncingCancelled(); + } + + void UpdateProgressBarEvent(double percentage) + { + syncingProgressBar.Value = (int)percentage; + } + #endregion + + #region Things for "Error" page + private void buttonTryAgain_Click(object sender, EventArgs e) + { + Controller.ErrorPageCompleted(); + } + #endregion + + #region Thigngs for "Finish" page + private void buttonFinished_Click (object sender, EventArgs e) { + Controller.FinishPageCompleted(); + } + + private void buttonOpenFolder_Click (object sender, EventArgs e) { + Controller.OpenFolderClicked(); + } + #endregion + } +} + +public class TreeView : System.Windows.Forms.TreeView { + + protected override void OnDrawNode (DrawTreeNodeEventArgs e) { + e.Graphics.DrawString (e.Node.Text.Split (';') [0], new Font (Font.SystemFontName, 13), + new SolidBrush (Color.Black), e.Bounds.X, e.Bounds.Y); + e.Graphics.DrawString (e.Node.Text.Split (';') [1], new Font (Font.SystemFontName, 9), + new SolidBrush (Color.Black), e.Bounds.X + 10, e.Bounds.Y + 15); + } +} + +public class TreeNode : System.Windows.Forms.TreeNode { + public TreeNode (string text) { + this.Text = text; + } +} + diff --git a/SparkleShare/Windows/SparkleSetup.resx b/SparkleShare/Windows/SparkleSetup.resx new file mode 100644 index 00000000..a82557eb --- /dev/null +++ b/SparkleShare/Windows/SparkleSetup.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + First, have you tried turning it off and on again? is the address we've compiled {Controller.SyncingFolder} from the information you entered. Does this look correct? + +The host needs to know who you are. Have you uploaded the key that sits in your SparkleShare folder? + + + \ No newline at end of file diff --git a/SparkleShare/Windows/SparkleShare.csproj b/SparkleShare/Windows/SparkleShare.csproj new file mode 100644 index 00000000..065690cf --- /dev/null +++ b/SparkleShare/Windows/SparkleShare.csproj @@ -0,0 +1,422 @@ + + + + Debug + AnyCPU + 9.0.30729 + {728483AA-E34B-4441-BF2C-C8BC2901E4E0} + WinExe + SparkleShare + 2.0 + SparkleShare + + + 3.5 + + + false + v3.5 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + ..\..\data\icons\sparkleshare.ico + + + + + true + full + false + ..\..\bin + DEBUG + prompt + 4 + x86 + AllRules.ruleset + false + + + none + false + ..\..\bin + prompt + 4 + AllRules.ruleset + x86 + + + + + ..\..\bin\CefSharp.dll + + + False + ..\..\tools\gettext-cs-utils\Gettext.CsUtils\Core\Gettext.Cs\bin\Release\Gettext.Cs.dll + + + + + 3.5 + + + + + + + + + GlobalAssemblyInfo.cs + True + True + GlobalAssemblyInfo.tt + + + SparkleBubblesController.cs + + + SparkleControllerBase.cs + + + SparkleExtensions.cs + + + SparkleInvite.cs + + + SparkleOptions.cs + + + SparklePlugin.cs + + + SparkleStatusIconController.cs + + + + + Component + + + + True + True + Icons.resx + + + Form + + + Notification.cs + + + True + True + Resources.resx + + + Form + + + SparkleAbout.cs + + + Form + + + + + + + + Form + + + SparkleEventLog.cs + + + Form + + + SparkleSetup.cs + + + + + + Component + + + True + True + Strings.tt + + + + + {2C914413-B31C-4362-93C7-1AE34F09112A} + SparkleLib + + + + + + + + + + + + + + + + + + + + + False + .NET Framework 2.0 %28x86%29 + true + + + False + .NET Framework 3.0 %28x86%29 + false + + + False + .NET Framework 3.5 + false + + + + + + + + + GlobalAssemblyInfo.tt + TextTemplatingFileGenerator + GlobalAssemblyInfo.cs + + + + $(ProjectDir)transform_tt.cmd + + + + True + True + Icons.tt + Designer + ResXFileCodeGenerator + Icons.Designer.cs + + + Notification.cs + Designer + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + SparkleAbout.cs + Designer + + + SparkleEventLog.cs + Designer + + + SparkleSetup.cs + Designer + + + + + TextTemplatingFileGenerator + Icons.resx + + + + + plugins\bitbucket.png + Always + + + plugins\github.png + Always + + + plugins\gitorious.png + Always + + + plugins\gnome.png + Always + + + plugins\own-server.png + Always + + + + + plugins\bitbucket.xml + Always + + + plugins\github.xml + Always + + + plugins\gitorious.xml + Always + + + plugins\gnome.xml + Always + + + plugins\own-server.xml + Always + + + po\ar.po + Always + + + po\bg.po + Always + + + po\ca.po + Always + + + po\cs_CZ.po + Always + + + po\da.po + Always + + + po\de.po + Always + + + po\el.po + Always + + + po\eo.po + Always + + + po\es.po + Always + + + po\fi.po + Always + + + po\fr.po + Always + + + po\he.po + Always + + + po\hu.po + Always + + + po\it.po + Always + + + po\ja.po + Always + + + po\nl.po + Always + + + po\nn_NO.po + Always + + + po\no_NO.po + Always + + + po\pl.po + Always + + + po\pt_BR.po + Always + + + po\ru.po + Always + + + po\sk.po + Always + + + po\sl.po + Always + + + po\sr_RS.po + Always + + + po\sv.po + Always + + + po\te.po + Always + + + po\uk.po + Always + + + po\zh_CN.po + Always + + + po\zh_TW.po + Always + + + TextTemplatingFileGenerator + Strings.cs + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/SparkleShare.sln b/SparkleShare/Windows/SparkleShare.sln new file mode 100644 index 00000000..5f5b3a2b --- /dev/null +++ b/SparkleShare/Windows/SparkleShare.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SparkleShare", "SparkleShare.csproj", "{728483AA-E34B-4441-BF2C-C8BC2901E4E0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SparkleLib", "..\..\SparkleLib\windows\SparkleLib.csproj", "{2C914413-B31C-4362-93C7-1AE34F09112A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SparkleShareInviteOpen", "SparkleShareInviteOpen\SparkleShareInviteOpen.csproj", "{1DB5492D-B897-4A5E-8DD7-175EC65F52F2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {728483AA-E34B-4441-BF2C-C8BC2901E4E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {728483AA-E34B-4441-BF2C-C8BC2901E4E0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {728483AA-E34B-4441-BF2C-C8BC2901E4E0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {728483AA-E34B-4441-BF2C-C8BC2901E4E0}.Release|Any CPU.Build.0 = Release|Any CPU + {2C914413-B31C-4362-93C7-1AE34F09112A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2C914413-B31C-4362-93C7-1AE34F09112A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2C914413-B31C-4362-93C7-1AE34F09112A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2C914413-B31C-4362-93C7-1AE34F09112A}.Release|Any CPU.Build.0 = Release|Any CPU + {1DB5492D-B897-4A5E-8DD7-175EC65F52F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1DB5492D-B897-4A5E-8DD7-175EC65F52F2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1DB5492D-B897-4A5E-8DD7-175EC65F52F2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1DB5492D-B897-4A5E-8DD7-175EC65F52F2}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(MonoDevelopProperties) = preSolution + StartupItem = SparkleShare.csproj + outputpath = bin + name = SparkleShare + EndGlobalSection +EndGlobal diff --git a/SparkleShare/Windows/SparkleShare.wxs b/SparkleShare/Windows/SparkleShare.wxs new file mode 100644 index 00000000..308374f4 --- /dev/null +++ b/SparkleShare/Windows/SparkleShare.wxs @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Not Installed + + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/SparkleShareInviteOpen/Properties/AssemblyInfo.cs b/SparkleShare/Windows/SparkleShareInviteOpen/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..43f12384 --- /dev/null +++ b/SparkleShare/Windows/SparkleShareInviteOpen/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// La información general sobre un ensamblado se controla mediante el siguiente +// conjunto de atributos. Cambie estos atributos para modificar la información +// asociada con un ensamblado. +[assembly: AssemblyTitle("SparkleShareInviteOpen")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SparkleShareInviteOpen")] +[assembly: AssemblyCopyright("Copyright © 2012")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles +// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde +// COM, establezca el atributo ComVisible como true en este tipo. +[assembly: ComVisible(false)] + +// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM +[assembly: Guid("5d15209c-88a2-4d7f-9934-af24b8c90c55")] + +// La información de versión de un ensamblado consta de los cuatro valores siguientes: +// +// Versión principal +// Versión secundaria +// Número de versión de compilación +// Revisión +// +// Puede especificar todos los valores o establecer como predeterminados los números de versión de compilación y de revisión +// mediante el asterisco ('*'), como se muestra a continuación: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SparkleShare/Windows/SparkleShareInviteOpen/SparkleShareInviteOpen.csproj b/SparkleShare/Windows/SparkleShareInviteOpen/SparkleShareInviteOpen.csproj new file mode 100644 index 00000000..9e49f1df --- /dev/null +++ b/SparkleShare/Windows/SparkleShareInviteOpen/SparkleShareInviteOpen.csproj @@ -0,0 +1,51 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {1DB5492D-B897-4A5E-8DD7-175EC65F52F2} + Exe + Properties + SparkleShareInviteOpen + SparkleShareInviteOpen + v3.5 + 512 + ..\..\..\data\icons\sparkleshare.ico + + + true + full + false + ..\..\..\bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + ..\..\..\bin\ + TRACE + prompt + 4 + + + + + + + sparkleshare-invite-open.cs + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/SparkleStatusIcon.cs b/SparkleShare/Windows/SparkleStatusIcon.cs new file mode 100644 index 00000000..15a3365f --- /dev/null +++ b/SparkleShare/Windows/SparkleStatusIcon.cs @@ -0,0 +1,386 @@ +// SparkleShare, a collaboration and sharing tool. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can 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 . + + +using System; +using System.IO; + +using SparkleLib; +using System.Windows.Forms; +using System.Drawing; + +using System.Runtime.InteropServices; + +namespace SparkleShare { + + // The statusicon that stays in the + // user's notification area + public class SparkleStatusIcon : IDisposable { + + public SparkleStatusIconController Controller = new SparkleStatusIconController(); + + private Timer Animation; + private Bitmap [] AnimationFrames; + private int FrameNumber; + private string StateText; + + private ToolStripItem status_menu_item; + private NotifyIcon status_icon; + + // Short alias for the translations + public static string _ (string s) + { + return Program._ (s); + } + + + public SparkleStatusIcon () + { + AnimationFrames = CreateAnimationFrames (); + Animation = CreateAnimation (); + + this.status_icon = new NotifyIcon (); + status_icon.Text = "SparkleShare"; + status_icon.Icon = Icons.sparkleshare; + status_icon.Visible = true; + + CreateMenu (); + SetNormalState (); + + Program.Controller.FolderListChanged += delegate { + status_icon.ContextMenuStrip.SafeInvoke ((Action)delegate { + SetNormalState (); + CreateMenu (); + }); + }; + + Program.Controller.OnIdle += delegate { + status_icon.ContextMenuStrip.SafeInvoke ((Action)delegate { + SetNormalState (); + UpdateMenu (); + }); + }; + + Program.Controller.OnSyncing += delegate { + status_icon.ContextMenuStrip.SafeInvoke ((Action)delegate { + SetAnimationState (); + UpdateMenu (); + }); + }; + + Program.Controller.OnError += delegate { + status_icon.ContextMenuStrip.SafeInvoke ((Action)delegate { + SetNormalState (true); + UpdateMenu (); + }); + }; + } + + + // Slices up the graphic that contains the + // animation frames. + private Bitmap [] CreateAnimationFrames () + { + Bitmap [] animation_frames = new Bitmap [5]; + animation_frames [0] = Icons.process_syncing_sparkleshare_i_24; + animation_frames [1] = Icons.process_syncing_sparkleshare_ii_24; + animation_frames [2] = Icons.process_syncing_sparkleshare_iii_24; + animation_frames [3] = Icons.process_syncing_sparkleshare_iiii_24; + animation_frames [4] = Icons.process_syncing_sparkleshare_iiiii_24; + + return animation_frames; + } + + [DllImport("user32.dll", EntryPoint = "DestroyIcon")] + static extern bool DestroyIcon(IntPtr hIcon); + + private Icon GetIconFromBitmap (Bitmap bitmap) + { + IntPtr unmanagedIcon = bitmap.GetHicon(); + Icon icon = (Icon)Icon.FromHandle(unmanagedIcon).Clone(); + DestroyIcon(unmanagedIcon); + return icon; + } + + // Creates the Animation that handles the syncing animation + private Timer CreateAnimation () + { + FrameNumber = 0; + + Timer Animation = new Timer () { + Interval = 35 + }; + + Animation.Tick += delegate { + if (FrameNumber < AnimationFrames.Length - 1) + FrameNumber++; + else + FrameNumber = 0; + + status_icon.ContextMenuStrip.SafeInvoke ((Action)delegate { + this.status_icon.Icon = GetIconFromBitmap( AnimationFrames [FrameNumber]); + }); + }; + + return Animation; + } + + + // Creates the menu that is popped up when the + // user clicks the status icon + public void CreateMenu () + { + ContextMenuStrip Menu = new ContextMenuStrip (); + + // The menu item showing the status and size of the SparkleShare folder + status_menu_item = new ToolStripLabel (StateText); + + Menu.Items.Add (status_menu_item); + Menu.Items.Add (new ToolStripSeparator ()); + + ToolStripMenuItem folder_item = new ToolStripMenuItem ("SparkleShare") { + Image = Icons.folder_sparkleshare_16 + }; + + folder_item.Click += delegate { + Program.Controller.OpenSparkleShareFolder (); + }; + + Menu.Items.Add (folder_item); + + if (Program.Controller.Folders.Count > 0) { + + // Creates a menu item for each repository with a link to their logs + foreach (string folder_name in Program.Controller.Folders) { + Bitmap folder_icon; + + if (Program.Controller.UnsyncedFolders.Contains (folder_name)) { + folder_icon = Icons.dialog_error_16; + } else { + folder_icon = Icons.sparkleshare_windows_status; + } + + ToolStripMenuItem subfolder_item = new ToolStripMenuItem (folder_name) { + Image = folder_icon + }; + + subfolder_item.Click += OpenFolderDelegate (folder_name); + Menu.Items.Add (subfolder_item); + } + + } else { + ToolStripMenuItem no_folders_item = new ToolStripMenuItem (_ ("No Remote Folders Yet")) { + Enabled = false + }; + + Menu.Items.Add (no_folders_item); + } + + Menu.Items.Add (new ToolStripSeparator ()); + + // Opens the wizard to add a new remote folder + ToolStripMenuItem sync_item = new ToolStripMenuItem (_ ("Add Hosted Project…")); + + if (Program.Controller.FirstRun) + sync_item.Enabled = false; + + sync_item.Click += delegate { + Controller.AddHostedProjectClicked(); + }; + + Menu.Items.Add (sync_item); + Menu.Items.Add (new ToolStripSeparator ()); + + ToolStripMenuItem recent_events_item = new ToolStripMenuItem (_ ("Open Recent Events")); + + if (Program.Controller.Folders.Count < 1) + recent_events_item.Enabled = false; + + recent_events_item.Click += delegate { + if (SparkleUI.EventLog == null) + SparkleUI.EventLog = new SparkleEventLog (); + + SparkleUI.EventLog.Show (); + SparkleUI.EventLog.BringToFront (); + }; + + Menu.Items.Add (recent_events_item); + + ToolStripMenuItem notify_item; + + if (Program.Controller.NotificationsEnabled) + notify_item = new ToolStripMenuItem (_ ("Turn Notifications Off")); + else + notify_item = new ToolStripMenuItem (_ ("Turn Notifications On")); + + notify_item.Click += delegate { + Program.Controller.ToggleNotifications (); + CreateMenu (); + }; + + Menu.Items.Add (notify_item); + Menu.Items.Add (new ToolStripSeparator ()); + + // A menu item that takes the user to http://www.sparkleshare.org/ + ToolStripMenuItem about_item = new ToolStripMenuItem (_ ("About SparkleShare")); + + about_item.Click += delegate { + if (SparkleUI.About == null) + SparkleUI.About = new SparkleAbout (); + + SparkleUI.About.Show (); + SparkleUI.About.BringToFront (); + }; + + Menu.Items.Add (about_item); + Menu.Items.Add (new ToolStripSeparator ()); + + // A menu item that quits the application + ToolStripMenuItem quit_item = new ToolStripMenuItem (_ ("Quit")); + + quit_item.Click += delegate { + Program.Controller.Quit (); + }; + + Menu.Items.Add (quit_item); + + status_icon.ContextMenuStrip = Menu; + } + + public void ShowBalloon (string title, string subtext, string image_path) + { + status_icon.BalloonTipText = title; + status_icon.BalloonTipText = subtext; + // TODO: Use the image pointed to by image_path + status_icon.BalloonTipIcon = ToolTipIcon.None; + status_icon.ShowBalloonTip (2 * 1000); + } + + + // A method reference that makes sure that opening the + // event log for each repository works correctly + private EventHandler OpenFolderDelegate (string name) + { + return delegate { + Program.Controller.OpenSparkleShareFolder (name); + }; + } + + + public void UpdateMenu () + { + status_menu_item.Text=StateText; + } + + + // The state when there's nothing going on + private void SetNormalState () + { + SetNormalState (false); + } + + + // The state when there's nothing going on + private void SetNormalState (bool error) + { + Animation.Stop (); + + if (Program.Controller.Folders.Count == 0) { + StateText = _("Welcome to SparkleShare!"); + + status_icon.ContextMenuStrip.SafeInvoke ((Action)delegate { + this.status_icon.Icon = GetIconFromBitmap (AnimationFrames [0]); + }); + + } else { + if (error) { + StateText = _("Not everything is synced"); + + status_icon.ContextMenuStrip.SafeInvoke ((Action)delegate { + this.status_icon.Icon = GetIconFromBitmap (Icons.sparkleshare_syncing_error_24); + }); + } else { + StateText = _("Up to date") + " (" + FolderSize + ")"; + status_icon.ContextMenuStrip.SafeInvoke ((Action)delegate { + this.status_icon.Icon = GetIconFromBitmap (AnimationFrames [0]); + }); + } + } + } + + + // The state when animating + private void SetAnimationState () + { + StateText = _("Syncing…"); + + if (!Animation.Enabled) + Animation.Start (); + } + + public string FolderSize + { + get + { + double size = 0; + + foreach (SparkleRepoBase repo in Program.Controller.Repositories) + size += repo.Size + repo.HistorySize; + + return Program.Controller.FormatSize(size); + } + } + + #region IDisposable Members + + public void Dispose () + { + status_icon.Dispose (); + } + + #endregion + } + + + public static class ControlExtention { + public static void SafeInvoke (this Control uiElement, Action updater, bool forceSynchronous) + { + if (uiElement == null) { + //throw new ArgumentNullException ("uiElement"); + return; + } + + if (uiElement.InvokeRequired) { + if (forceSynchronous) { + uiElement.Invoke ((Action)delegate { SafeInvoke (uiElement, updater, forceSynchronous); }); + } else { + uiElement.BeginInvoke ((Action)delegate { SafeInvoke (uiElement, updater, forceSynchronous); }); + } + } else { + if (uiElement.IsDisposed) { + throw new ObjectDisposedException ("Control is already disposed."); + } + + updater (); + } + } + public static void SafeInvoke (this Control uiElement, Action updater) + { + uiElement.SafeInvoke (updater, false); + } + + } +} diff --git a/SparkleShare/Windows/SparkleUIHelpers.cs b/SparkleShare/Windows/SparkleUIHelpers.cs new file mode 100644 index 00000000..91a905b0 --- /dev/null +++ b/SparkleShare/Windows/SparkleUIHelpers.cs @@ -0,0 +1,55 @@ +// SparkleShare, a collaboration and sharing tool. +// Copyright (C) 2010 Hylke Bons +// +// This program is free software: you can 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 . + +using System.Collections.Generic; +using System.Windows.Forms; +using SparkleLib; +using System; +using System.IO; +using System.Net; +using System.Security.Cryptography; +using System.Text; + +namespace SparkleShare { + + public static class SparkleUIHelpers { + + // Creates an MD5 hash of input + public static string GetMD5 (string s) + { + MD5 md5 = new MD5CryptoServiceProvider (); + Byte[] bytes = ASCIIEncoding.Default.GetBytes (s); + Byte[] encodedBytes = md5.ComputeHash (bytes); + return BitConverter.ToString (encodedBytes).ToLower ().Replace ("-", ""); + } + + public static string ToHex (this System.Drawing.Color color) + { + return String.Format ("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B); + } + + //http://stackoverflow.com/a/1499161/33499 + public static IEnumerable All (this Control.ControlCollection controls) + { + foreach (Control control in controls) { + foreach (Control grandChild in control.Controls.All ()) + yield return grandChild; + + yield return control; + } + } + } +} diff --git a/SparkleShare/Windows/Strings.cs b/SparkleShare/Windows/Strings.cs new file mode 100644 index 00000000..4e545d5e --- /dev/null +++ b/SparkleShare/Windows/Strings.cs @@ -0,0 +1,146 @@ + +// +// This code was generated by a tool. Any changes made manually will be lost +// the next time this code is regenerated. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; +using System.Threading; +using System.Configuration; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +namespace SparkleShare +{ + public class Strings + { + private static Object resourceManLock = new Object(); + private static System.Resources.ResourceManager resourceMan; + private static System.Globalization.CultureInfo resourceCulture; + + public const string ResourceName = "Strings"; + + private static string resourcesDir = GetSetting("ResourcesDir", "po"); + private static string fileFormat = GetSetting("ResourcesFileFormat", "{{culture}}.po"); + + private static string GetSetting(string setting, string defaultValue) + { + var section = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings"); + if (section == null) return defaultValue; + else return section[setting] ?? defaultValue; + } + + + /// + /// Resources directory used to retrieve files from. + /// + public static string ResourcesDirectory + { + get { return resourcesDir; } + set { resourcesDir = value; } + } + + /// + /// Format of the file based on culture and resource name. + /// + public static string FileFormat + { + get { return fileFormat; } + set { fileFormat = value; } + } + + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + public static System.Resources.ResourceManager ResourceManager + { + get + { + + if (object.ReferenceEquals(resourceMan, null)) + { + lock (resourceManLock) + { + if (object.ReferenceEquals(resourceMan, null)) + { + var directory = resourcesDir; + var mgr = new global::Gettext.Cs.GettextResourceManager(ResourceName, directory, fileFormat); + resourceMan = mgr; + } + } + } + + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + public static System.Globalization.CultureInfo Culture + { + get { return resourceCulture; } + set { resourceCulture = value; } + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(string t) + { + return T(null, t); + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t) + { + if (String.IsNullOrEmpty(t)) return t; + var translated = ResourceManager.GetString(t, info ?? resourceCulture); + return String.IsNullOrEmpty(translated) ? t : translated; + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(string t, params object[] parameters) + { + return T(null, t, parameters); + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t, params object[] parameters) + { + if (String.IsNullOrEmpty(t)) return t; + return String.Format(T(info, t), parameters); + } + + /// + /// Marks a string for future translation, does not translate it now. + /// + public static string M(string t) + { + return t; + } + + /// + /// Returns the resource set available for the specified culture. + /// + public static System.Resources.ResourceSet GetResourceSet(CultureInfo culture) + { + return ResourceManager.GetResourceSet(culture, true, true); + } + } +} + + diff --git a/SparkleShare/Windows/Strings.tt b/SparkleShare/Windows/Strings.tt new file mode 100644 index 00000000..15a29926 --- /dev/null +++ b/SparkleShare/Windows/Strings.tt @@ -0,0 +1,10 @@ +<#@ assembly name="System.Configuration" #> + +<# + this.ClassName = "Strings"; + this.ResourceName = "Strings"; + this.NamespaceName = "SparkleShare"; + this.DefaultResourceDir = "po"; + this.DefaultFileFormat = "{{culture}}.po"; +#> +<#@ include file="..\..\tools\gettext-cs-utils\Gettext.CsUtils\Core\Gettext.Cs\Templates\Strings.tt" #> diff --git a/SparkleShare/Windows/build.cmd b/SparkleShare/Windows/build.cmd new file mode 100644 index 00000000..7f86aa63 --- /dev/null +++ b/SparkleShare/Windows/build.cmd @@ -0,0 +1,35 @@ +@echo off + +call %~dp0\..\..\data\plugins\build.cmd + +set WinDirNet=%WinDir%\Microsoft.NET\Framework +set msbuild="%WinDirNet%\v3.5\msbuild.exe" +if not exist %msbuild% set msbuild="%WinDirNet%\v4.0.30319\msbuild.exe" +set wixBinDir=%WIX%\bin + +cd lib +copy * ..\..\..\bin +cd .. + +cp ..\..\data\icons\sparkleshare.ico ..\..\bin + +%msbuild% /t:Rebuild /p:Configuration=Release /p:Platform="AnyCPU" %~dp0\tools\gettext-cs-utils\Gettext.CsUtils\Core\Gettext.Cs\Gettext.Cs.csproj +%msbuild% /t:Rebuild /p:Configuration=Release /p:Platform="Any CPU" %~dp0\SparkleShare.sln + +if "%1"=="installer" ( + if exist "%wixBinDir%" ( + if exist "%~dp0\SparkleShare.msi" del "%~dp0\SparkleShare.msi" + "%wixBinDir%\heat.exe" dir "%~dp0\..\..\bin\msysgit" -cg msysGitComponentGroup -gg -scom -sreg -sfrag -srd -dr MSYSGIT_DIR -var wix.msysgitpath -o msysgit.wxs + "%wixBinDir%\heat.exe" dir "%~dp0\..\..\bin\po" -cg poComponentGroup -gg -scom -sreg -sfrag -srd -dr PO_DIR -var wix.podir -o po.wxs + "%wixBinDir%\heat.exe" dir "%~dp0\..\..\bin\plugins" -cg pluginsComponentGroup -gg -scom -sreg -sfrag -srd -dr PLUGINS_DIR -var wix.pluginsdir -o plugins.wxs + "%wixBinDir%\candle" "%~dp0\SparkleShare.wxs" -ext WixUIExtension -ext WixUtilExtension + "%wixBinDir%\candle" "%~dp0\msysgit.wxs" -ext WixUIExtension -ext WixUtilExtension + "%wixBinDir%\candle" "%~dp0\po.wxs" -ext WixUIExtension -ext WixUtilExtension + "%wixBinDir%\candle" "%~dp0\plugins.wxs" -ext WixUIExtension -ext WixUtilExtension + "%wixBinDir%\light" -ext WixUIExtension -ext WixUtilExtension Sparkleshare.wixobj msysgit.wixobj po.wixobj plugins.wixobj -droot="%~dp0\..\.." -dmsysgitpath="%~dp0\..\..\bin\msysgit" -dpodir="%~dp0\..\..\bin\po" -dpluginsdir="%~dp0\..\..\bin\plugins" -o SparkleShare.msi + if exist "%~dp0\SparkleShare.msi" echo SparkleShare.msi created. + ) else ( + echo Not building installer ^(could not find wix, Windows Installer XML toolset^) + echo wix is available at http://wix.sourceforge.net/ + ) +) else echo Not building installer, as it was not requested. ^(Issue "build.cmd installer" to build installer ^) diff --git a/SparkleShare/Windows/controls/ExampleTextBox.cs b/SparkleShare/Windows/controls/ExampleTextBox.cs new file mode 100644 index 00000000..c054afaf --- /dev/null +++ b/SparkleShare/Windows/controls/ExampleTextBox.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace SparkleShare.controls { + public class ExampleTextBox : TextBox { + + private bool ExampleTextActive = true; + private bool OnTextChangedActive = true; + private bool _focused = false; + + private string _ExampleText = ""; + public string ExampleText + { + get { return _ExampleText; } + set + { + _ExampleText = value; + if (ExampleTextActive) + ActivateExampleText (); + } + } + + public override string Text + { + get + { + if (ExampleTextActive) + return ""; + return base.Text; + } + set + { + if (String.IsNullOrEmpty (value)) { + ActivateExampleText (); + } else { + ExampleTextActive = false; + ForeColor = System.Drawing.SystemColors.WindowText; + base.Text = value; + } + } + } + + private void ActivateExampleText () + { + OnTextChangedActive = false; + base.Text = ExampleText; + OnTextChangedActive = true; + ExampleTextActive = true; + ForeColor = System.Drawing.SystemColors.InactiveCaptionText; + } + + protected override void OnTextChanged (EventArgs e) + { + if (!OnTextChangedActive) + return; + + bool Empty = String.IsNullOrEmpty (base.Text); + if (Empty) { + ActivateExampleText (); + SelectAll (); + } else if (ExampleTextActive) { + ExampleTextActive = false; + ForeColor = System.Drawing.SystemColors.WindowText; + } + base.OnTextChanged (e); + } + + protected override void OnEnter (EventArgs e) + { + base.OnEnter (e); + if (ExampleTextActive && MouseButtons == MouseButtons.None) { + SelectAll (); + _focused = true; + } + } + + protected override void OnLeave (EventArgs e) + { + base.OnLeave (e); + _focused = false; + } + + protected override void OnMouseUp (MouseEventArgs mevent) + { + base.OnMouseUp (mevent); + if (!_focused) { + if (ExampleTextActive && SelectionLength == 0) + SelectAll (); + _focused = true; + } + } + } +} diff --git a/SparkleShare/Windows/controls/TablessControl.cs b/SparkleShare/Windows/controls/TablessControl.cs new file mode 100644 index 00000000..0618f531 --- /dev/null +++ b/SparkleShare/Windows/controls/TablessControl.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace SparkleShare.controls { + public class TablessControl : TabControl { + protected override void WndProc (ref Message m) + { + if (m.Msg == 0x1328 && !DesignMode) + m.Result = (IntPtr)1; + else + base.WndProc (ref m); + } + + } +} diff --git a/SparkleShare/Windows/lib/CefSharp.dll b/SparkleShare/Windows/lib/CefSharp.dll new file mode 100644 index 00000000..6f871b69 Binary files /dev/null and b/SparkleShare/Windows/lib/CefSharp.dll differ diff --git a/SparkleShare/Windows/lib/avcodec-52.dll b/SparkleShare/Windows/lib/avcodec-52.dll new file mode 100644 index 00000000..433efbee Binary files /dev/null and b/SparkleShare/Windows/lib/avcodec-52.dll differ diff --git a/SparkleShare/Windows/lib/avformat-52.dll b/SparkleShare/Windows/lib/avformat-52.dll new file mode 100644 index 00000000..fa2e000e Binary files /dev/null and b/SparkleShare/Windows/lib/avformat-52.dll differ diff --git a/SparkleShare/Windows/lib/avutil-50.dll b/SparkleShare/Windows/lib/avutil-50.dll new file mode 100644 index 00000000..f01f3f3d Binary files /dev/null and b/SparkleShare/Windows/lib/avutil-50.dll differ diff --git a/SparkleShare/Windows/lib/icudt42.dll b/SparkleShare/Windows/lib/icudt42.dll new file mode 100644 index 00000000..d61ac0b0 Binary files /dev/null and b/SparkleShare/Windows/lib/icudt42.dll differ diff --git a/SparkleShare/Windows/lib/libcef.dll b/SparkleShare/Windows/lib/libcef.dll new file mode 100644 index 00000000..9ea64973 Binary files /dev/null and b/SparkleShare/Windows/lib/libcef.dll differ diff --git a/SparkleShare/Windows/sparkleshare.ico b/SparkleShare/Windows/sparkleshare.ico new file mode 100644 index 00000000..2e88830e Binary files /dev/null and b/SparkleShare/Windows/sparkleshare.ico differ diff --git a/SparkleShare/Windows/tools/TextTemplating/.gitattributes b/SparkleShare/Windows/tools/TextTemplating/.gitattributes new file mode 100644 index 00000000..4cadb26b --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/.gitattributes @@ -0,0 +1,2 @@ +.gitattributes eol=lf +.gitmodules eol=lf diff --git a/SparkleShare/Windows/tools/TextTemplating/.gitignore b/SparkleShare/Windows/tools/TextTemplating/.gitignore new file mode 100644 index 00000000..335c1472 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/.gitignore @@ -0,0 +1,11 @@ +*~ +*.bak +*.suo +*.user +*.sln.cache +bin/ +obj/ +_ReSharper.*/ +_UpgradeReport_Files/ +Backup/ +UpgradeLog.XML diff --git a/SparkleShare/Windows/tools/TextTemplating/ChangeLog b/SparkleShare/Windows/tools/TextTemplating/ChangeLog new file mode 100644 index 00000000..b50bf135 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/ChangeLog @@ -0,0 +1,9 @@ +2009-08-12 Michael Hutchinson + + * Makefile.am: + * TextTransform: + * Mono.TextTemplating: + * Mono.TextTemplating.Tests: + * MonoDevelop.TextTemplating: Include the ASP.NET MVC and + TextTemplating addins in the main solution and build. + diff --git a/SparkleShare/Windows/tools/TextTemplating/Makefile.am b/SparkleShare/Windows/tools/TextTemplating/Makefile.am new file mode 100644 index 00000000..f0cb7546 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Makefile.am @@ -0,0 +1,4 @@ +SUBDIRS = \ + Mono.TextTemplating \ + TextTransform \ + MonoDevelop.TextTemplating diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/ChangeLog b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/ChangeLog new file mode 100644 index 00000000..061fc503 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/ChangeLog @@ -0,0 +1,65 @@ +2009-12-11 Michael Hutchinson + + * Mono.TextTemplating.Tests.csproj: Don't local-copy nunit. + +2009-11-27 Olivier Dagenais + + * GenerationTests.cs: Make tests independent of the runtime + they are running under by stripping the "autogenerated" + comment (i.e. the first 9 lines). + +2009-10-29 Lluis Sanchez Gual + + * Mono.TextTemplating.Tests.csproj: Flush. + +2009-08-13 Lluis Sanchez Gual + + * DummyHost.cs: Fix windows build. + +2009-08-13 Michael Hutchinson + + * Mono.TextTemplating.Tests.csproj: Use assembly refs for + nunit. + +2009-08-12 Michael Hutchinson + + * Mono.TextTemplating.Tests.csproj: Include the ASP.NET MVC + and TextTemplating addins in the main solution and build. + +2009-04-13 Michael Hutchinson + + * GenerationTests.cs: Add tests for Windows/Mac newlines. + +2009-04-03 Michael Hutchinson + + * Mono.TextTemplating.Tests.csproj: Updated. + + * GenerationTests.cs: Add test for C# output. + + * ParsingTests.cs: Track dummy host name change. + + * DummyHost.cs: Add more functionality to dummy host. + +2009-03-13 Michael Hutchinson + + * Mono.TextTemplating.Tests.csproj: Move output dir from + ../bin to ../build. + +2009-03-13 Michael Hutchinson + + * Mono.TextTemplating.Tests.csproj: Fix output directory. + +2009-03-12 Michael Hutchinson + + * Mono.TextTemplating.Tests.csproj: Updated. + + * ParsingTests.cs: Add parser test. + + * DummyHost.cs: Dummy templating host. + +2009-03-12 Michael Hutchinson + + * Mono.TextTemplating.Tests.csproj: Add tests. + + * ParsingTests.cs: Tokeniser state/value/location test. + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/DummyHost.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/DummyHost.cs new file mode 100644 index 00000000..027a2ddc --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/DummyHost.cs @@ -0,0 +1,113 @@ +// +// IncludeFileProviderHost.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using Microsoft.VisualStudio.TextTemplating; + +namespace Mono.TextTemplating.Tests +{ + + public class DummyHost : ITextTemplatingEngineHost + { + public readonly Dictionary Locations = new Dictionary (); + public readonly Dictionary Contents = new Dictionary (); + public readonly Dictionary HostOptions = new Dictionary (); + List standardAssemblyReferences = new List (); + List standardImports = new List (); + public readonly CompilerErrorCollection Errors = new CompilerErrorCollection (); + public readonly Dictionary DirectiveProcessors = new Dictionary (); + + public virtual object GetHostOption (string optionName) + { + object o; + HostOptions.TryGetValue (optionName, out o); + return o; + } + + public virtual bool LoadIncludeText (string requestFileName, out string content, out string location) + { + content = null; + return Locations.TryGetValue (requestFileName, out location) + && Contents.TryGetValue (requestFileName, out content); + } + + public virtual void LogErrors (CompilerErrorCollection errors) + { + Errors.AddRange (errors); + } + + public virtual AppDomain ProvideTemplatingAppDomain (string content) + { + return null; + } + + public virtual string ResolveAssemblyReference (string assemblyReference) + { + throw new System.NotImplementedException(); + } + + public virtual Type ResolveDirectiveProcessor (string processorName) + { + Type t; + DirectiveProcessors.TryGetValue (processorName, out t); + return t; + } + + public virtual string ResolveParameterValue (string directiveId, string processorName, string parameterName) + { + throw new System.NotImplementedException(); + } + + public virtual string ResolvePath (string path) + { + throw new System.NotImplementedException(); + } + + public virtual void SetFileExtension (string extension) + { + throw new System.NotImplementedException(); + } + + public virtual void SetOutputEncoding (System.Text.Encoding encoding, bool fromOutputDirective) + { + throw new System.NotImplementedException(); + } + + public virtual IList StandardAssemblyReferences { + get { return standardAssemblyReferences; } + } + + public virtual IList StandardImports { + get { return standardImports; } + } + + public virtual string TemplateFile { + get; set; + } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/GenerationTests.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/GenerationTests.cs new file mode 100644 index 00000000..1a4bd2b4 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/GenerationTests.cs @@ -0,0 +1,171 @@ +// +// GenerationTests.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.IO; +using NUnit.Framework; +using Microsoft.VisualStudio.TextTemplating; + +namespace Mono.TextTemplating.Tests +{ + + + [TestFixture] + public class GenerationTests + { + [Test] + public void Generate () + { + string Input = ParsingTests.ParseSample1; + string Output = OutputSample1; + Generate (Input, Output, "\n"); + } + + [Test] + public void GenerateMacNewlines () + { + string MacInput = ParsingTests.ParseSample1.Replace ("\n", "\r"); + string MacOutput = OutputSample1.Replace ("\\n", "\\r").Replace ("\n", "\r");; + Generate (MacInput, MacOutput, "\r"); + } + + [Test] + public void GenerateWindowsNewlines () + { + string WinInput = ParsingTests.ParseSample1.Replace ("\n", "\r\n"); + string WinOutput = OutputSample1.Replace ("\\n", "\\r\\n").Replace ("\n", "\r\n"); + Generate (WinInput, WinOutput, "\r\n"); + } + + //NOTE: we set the newline property on the code generator so that the whole files has matching newlines, + // in order to match the newlines in the verbatim code blocks + void Generate (string input, string expectedOutput, string newline) + { + DummyHost host = new DummyHost (); + string className = "GeneratedTextTransformation4f504ca0"; + string code = GenerateCode (host, input, className, newline); + Assert.AreEqual (0, host.Errors.Count); + Assert.AreEqual (expectedOutput, TemplatingEngineHelper.StripHeader (code, newline)); + } + + #region Helpers + + string GenerateCode (ITextTemplatingEngineHost host, string content, string name, string generatorNewline) + { + ParsedTemplate pt = ParsedTemplate.FromText (content, host); + if (pt.Errors.HasErrors) { + host.LogErrors (pt.Errors); + return null; + } + + TemplateSettings settings = TemplatingEngine.GetSettings (host, pt); + if (name != null) + settings.Name = name; + if (pt.Errors.HasErrors) { + host.LogErrors (pt.Errors); + return null; + } + + var ccu = TemplatingEngine.GenerateCompileUnit (host, content, pt, settings); + if (pt.Errors.HasErrors) { + host.LogErrors (pt.Errors); + return null; + } + + var opts = new System.CodeDom.Compiler.CodeGeneratorOptions (); + using (var writer = new System.IO.StringWriter ()) { + writer.NewLine = generatorNewline; + settings.Provider.GenerateCodeFromCompileUnit (ccu, writer, opts); + return writer.ToString (); + } + } + + #endregion + + #region Expected output strings + + public static string OutputSample1 = +@" +namespace Microsoft.VisualStudio.TextTemplating { + + + public partial class GeneratedTextTransformation4f504ca0 : global::Microsoft.VisualStudio.TextTemplating.TextTransformation { + + + #line 9 """" + +baz \#> + + #line default + #line hidden + + public override string TransformText() { + this.GenerationEnvironment = null; + + #line 2 """" + this.Write(""Line One\nLine Two\n""); + + #line default + #line hidden + + #line 4 """" + +foo + + + #line default + #line hidden + + #line 7 """" + this.Write(""Line Three ""); + + #line default + #line hidden + + #line 7 """" + this.Write(global::Microsoft.VisualStudio.TextTemplating.ToStringHelper.ToStringWithCulture( bar )); + + #line default + #line hidden + + #line 7 """" + this.Write(""\nLine Four\n""); + + #line default + #line hidden + return this.GenerationEnvironment.ToString(); + } + + protected override void Initialize() { + base.Initialize(); + } + } +} +"; + #endregion + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/Mono.TextTemplating.Tests.csproj b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/Mono.TextTemplating.Tests.csproj new file mode 100644 index 00000000..75860807 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/Mono.TextTemplating.Tests.csproj @@ -0,0 +1,55 @@ + + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {CB590106-8331-4CBE-8131-B154E7BF79E1} + Library + Mono.TextTemplating.Tests + Mono.TextTemplating.Tests + + + true + full + false + ..\bin + DEBUG + prompt + 4 + + + none + false + ..\bin + prompt + 4 + + + + + ..\NUnit\lib\nunit.core.dll + False + + + ..\NUnit\lib\nunit.framework.dll + False + + + + + + + + + + + + {A2364D6A-00EF-417C-80A6-815726C70032} + Mono.TextTemplating + False + + + + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/ParsingTests.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/ParsingTests.cs new file mode 100644 index 00000000..5e247509 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/ParsingTests.cs @@ -0,0 +1,191 @@ +// +// Test.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using NUnit.Framework; + +namespace Mono.TextTemplating.Tests +{ + + + [TestFixture] + public class ParsingTests + { + public static string ParseSample1 = +@"<#@ template language=""C#v3.5"" #> +Line One +Line Two +<# +foo +#> +Line Three <#= bar #> +Line Four +<#+ +baz \#> +#> +"; + + [Test] + public void TokenTest () + { + string tf = "test.input"; + Tokeniser tk = new Tokeniser (tf, ParseSample1); + + //line 1 + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 1, 1), tk.Location); + Assert.AreEqual (State.Content, tk.State); + Assert.AreEqual ("", tk.Value); + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (State.Directive, tk.State); + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 1, 5), tk.Location); + Assert.AreEqual (State.DirectiveName, tk.State); + Assert.AreEqual ("template", tk.Value); + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (State.Directive, tk.State); + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 1, 14), tk.Location); + Assert.AreEqual (State.DirectiveName, tk.State); + Assert.AreEqual ("language", tk.Value); + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (State.Directive, tk.State); + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (State.DirectiveValue, tk.State); + Assert.AreEqual (new Location (tf, 1, 23), tk.Location); + Assert.AreEqual ("C#v3.5", tk.Value); + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (State.Directive, tk.State); + + //line 2, 3 + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 2, 1), tk.Location); + Assert.AreEqual (State.Content, tk.State); + Assert.AreEqual ("Line One\nLine Two\n", tk.Value); + + //line 4, 5, 6 + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 4, 1), tk.TagStartLocation); + Assert.AreEqual (new Location (tf, 4, 3), tk.Location); + Assert.AreEqual (new Location (tf, 6, 3), tk.TagEndLocation); + Assert.AreEqual (State.Block, tk.State); + Assert.AreEqual ("\nfoo\n", tk.Value); + + //line 7 + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 7, 1), tk.Location); + Assert.AreEqual (State.Content, tk.State); + Assert.AreEqual ("Line Three ", tk.Value); + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 7, 12), tk.TagStartLocation); + Assert.AreEqual (new Location (tf, 7, 15), tk.Location); + Assert.AreEqual (new Location (tf, 7, 22), tk.TagEndLocation); + Assert.AreEqual (State.Expression, tk.State); + Assert.AreEqual (" bar ", tk.Value); + + //line 8 + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 7, 22), tk.Location); + Assert.AreEqual (State.Content, tk.State); + Assert.AreEqual ("\nLine Four\n", tk.Value); + + //line 9, 10, 11 + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 9, 1), tk.TagStartLocation); + Assert.AreEqual (new Location (tf, 9, 4), tk.Location); + Assert.AreEqual (new Location (tf, 11, 3), tk.TagEndLocation); + Assert.AreEqual (State.Helper, tk.State); + Assert.AreEqual (" \nbaz \\#>\n", tk.Value); + + //line 12 + Assert.IsTrue (tk.Advance ()); + Assert.AreEqual (new Location (tf, 12, 1), tk.Location); + Assert.AreEqual (State.Content, tk.State); + Assert.AreEqual ("", tk.Value); + + //EOF + Assert.IsFalse (tk.Advance ()); + Assert.AreEqual (new Location (tf, 12, 1), tk.Location); + Assert.AreEqual (State.EOF, tk.State); + } + + [Test] + public void ParseTest () + { + string tf = "test.input"; + + ParsedTemplate pt = new ParsedTemplate ("test.input"); + Tokeniser tk = new Tokeniser (tf, ParseSample1); + DummyHost host = new DummyHost (); + pt.Parse (host, tk); + + Assert.AreEqual (0, pt.Errors.Count); + var content = new List (pt.Content); + var dirs = new List (pt.Directives); + + Assert.AreEqual (1, dirs.Count); + Assert.AreEqual (6, content.Count); + + Assert.AreEqual ("template", dirs[0].Name); + Assert.AreEqual (1, dirs[0].Attributes.Count); + Assert.AreEqual ("C#v3.5", dirs[0].Attributes["language"]); + Assert.AreEqual (new Location (tf, 1, 1), dirs[0].TagStartLocation); + Assert.AreEqual (new Location (tf, 1, 34), dirs[0].EndLocation); + + Assert.AreEqual ("Line One\nLine Two\n", content[0].Text); + Assert.AreEqual ("\nfoo\n", content[1].Text); + Assert.AreEqual ("Line Three ", content[2].Text); + Assert.AreEqual (" bar ", content[3].Text); + Assert.AreEqual ("\nLine Four\n", content[4].Text); + Assert.AreEqual (" \nbaz \\#>\n", content[5].Text); + + Assert.AreEqual (SegmentType.Content, content[0].Type); + Assert.AreEqual (SegmentType.Block, content[1].Type); + Assert.AreEqual (SegmentType.Content, content[2].Type); + Assert.AreEqual (SegmentType.Expression, content[3].Type); + Assert.AreEqual (SegmentType.Content, content[4].Type); + Assert.AreEqual (SegmentType.Helper, content[5].Type); + + Assert.AreEqual (new Location (tf, 4, 1), content[1].TagStartLocation); + Assert.AreEqual (new Location (tf, 7, 12), content[3].TagStartLocation); + Assert.AreEqual (new Location (tf, 9, 1), content[5].TagStartLocation); + + Assert.AreEqual (new Location (tf, 2, 1), content[0].StartLocation); + Assert.AreEqual (new Location (tf, 4, 3), content[1].StartLocation); + Assert.AreEqual (new Location (tf, 7, 1), content[2].StartLocation); + Assert.AreEqual (new Location (tf, 7, 15), content[3].StartLocation); + Assert.AreEqual (new Location (tf, 7, 22), content[4].StartLocation); + Assert.AreEqual (new Location (tf, 9, 4), content[5].StartLocation); + + Assert.AreEqual (new Location (tf, 6, 3), content[1].EndLocation); + Assert.AreEqual (new Location (tf, 7, 22), content[3].EndLocation); + Assert.AreEqual (new Location (tf, 11, 3), content[5].EndLocation); + } + + + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs new file mode 100644 index 00000000..02bcab11 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs @@ -0,0 +1,246 @@ +// +// TemplateEnginePreprocessTemplateTests.cs +// +// Author: +// Matt Ward +// +// Copyright (c) 2010 Matt Ward +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.IO; +using NUnit.Framework; +using Microsoft.VisualStudio.TextTemplating; + +namespace Mono.TextTemplating.Tests +{ + [TestFixture] + public class TemplateEnginePreprocessTemplateTests + { + [Test] + public void Preprocess () + { + string input = + "<#@ template language=\"C#\" #>\r\n" + + "Test\r\n"; + + string expectedOutput = OutputSample1; + string output = Preprocess (input); + + Assert.AreEqual (expectedOutput, output); + } + + #region Helpers + + string Preprocess (string input) + { + DummyHost host = new DummyHost (); + string className = "PreprocessedTemplate"; + string classNamespace = "Templating"; + string language = null; + string[] references = null; + + TemplatingEngine engine = new TemplatingEngine (); + string output = engine.PreprocessTemplate (input, host, className, classNamespace, out language, out references); + output = output.Replace ("\r\n", "\n"); + return TemplatingEngineHelper.StripHeader (output, "\n"); + } + + #endregion + + #region Expected output strings + + public static string OutputSample1 = +@" +namespace Templating { + + + public partial class PreprocessedTemplate : PreprocessedTemplateBase { + + public virtual string TransformText() { + this.GenerationEnvironment = null; + + #line 2 """" + this.Write(""Test\r\n""); + + #line default + #line hidden + return this.GenerationEnvironment.ToString(); + } + + protected virtual void Initialize() { + } + } + + public class PreprocessedTemplateBase { + + private global::System.Text.StringBuilder builder; + + private global::System.Collections.Generic.IDictionary session; + + private global::System.CodeDom.Compiler.CompilerErrorCollection errors; + + private string currentIndent = string.Empty; + + private global::System.Collections.Generic.Stack indents; + + private ToStringInstanceHelper _toStringHelper = new ToStringInstanceHelper(); + + public virtual global::System.Collections.Generic.IDictionary Session { + get { + return this.session; + } + set { + this.session = value; + } + } + + public global::System.Text.StringBuilder GenerationEnvironment { + get { + if ((this.builder == null)) { + this.builder = new global::System.Text.StringBuilder(); + } + return this.builder; + } + set { + this.builder = value; + } + } + + protected global::System.CodeDom.Compiler.CompilerErrorCollection Errors { + get { + if ((this.errors == null)) { + this.errors = new global::System.CodeDom.Compiler.CompilerErrorCollection(); + } + return this.errors; + } + } + + public string CurrentIndent { + get { + return this.currentIndent; + } + } + + private global::System.Collections.Generic.Stack Indents { + get { + if ((this.indents == null)) { + this.indents = new global::System.Collections.Generic.Stack(); + } + return this.indents; + } + } + + public ToStringInstanceHelper ToStringHelper { + get { + return this._toStringHelper; + } + } + + public void Error(string message) { + this.Errors.Add(new global::System.CodeDom.Compiler.CompilerError(null, -1, -1, null, message)); + } + + public void Warning(string message) { + global::System.CodeDom.Compiler.CompilerError val = new global::System.CodeDom.Compiler.CompilerError(null, -1, -1, null, message); + val.IsWarning = true; + this.Errors.Add(val); + } + + public string PopIndent() { + if ((this.Indents.Count == 0)) { + return string.Empty; + } + int lastPos = (this.currentIndent.Length - this.Indents.Pop()); + string last = this.currentIndent.Substring(lastPos); + this.currentIndent = this.currentIndent.Substring(0, lastPos); + return last; + } + + public void PushIndent(string indent) { + this.Indents.Push(indent.Length); + this.currentIndent = (this.currentIndent + indent); + } + + public void ClearIndent() { + this.currentIndent = string.Empty; + this.Indents.Clear(); + } + + public void Write(string textToAppend) { + this.GenerationEnvironment.Append(textToAppend); + } + + public void Write(string format, params object[] args) { + this.GenerationEnvironment.AppendFormat(format, args); + } + + public void WriteLine(string textToAppend) { + this.GenerationEnvironment.Append(this.currentIndent); + this.GenerationEnvironment.AppendLine(textToAppend); + } + + public void WriteLine(string format, params object[] args) { + this.GenerationEnvironment.Append(this.currentIndent); + this.GenerationEnvironment.AppendFormat(format, args); + this.GenerationEnvironment.AppendLine(); + } + + public class ToStringInstanceHelper { + + private global::System.IFormatProvider formatProvider = global::System.Globalization.CultureInfo.InvariantCulture; + + public global::System.IFormatProvider FormatProvider { + get { + return this.formatProvider; + } + set { + if ((this.formatProvider == null)) { + throw new global::System.ArgumentNullException(""formatProvider""); + } + this.formatProvider = value; + } + } + + public string ToStringWithCulture(object objectToConvert) { + if ((objectToConvert == null)) { + throw new global::System.ArgumentNullException(""objectToConvert""); + } + global::System.Type type = objectToConvert.GetType(); + global::System.Type iConvertibleType = typeof(global::System.IConvertible); + if (iConvertibleType.IsAssignableFrom(type)) { + return ((global::System.IConvertible)(objectToConvert)).ToString(this.formatProvider); + } + global::System.Reflection.MethodInfo methInfo = type.GetMethod(""ToString"", new global::System.Type[] { + iConvertibleType}); + if ((methInfo != null)) { + return ((string)(methInfo.Invoke(objectToConvert, new object[] { + this.formatProvider}))); + } + return objectToConvert.ToString(); + } + } + } +} +"; + #endregion + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/TemplatingEngineHelper.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/TemplatingEngineHelper.cs new file mode 100644 index 00000000..6238f7a8 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating.Tests/TemplatingEngineHelper.cs @@ -0,0 +1,51 @@ +// +// Test.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.IO; + +namespace Mono.TextTemplating.Tests +{ + public static class TemplatingEngineHelper + { + public static string StripHeader (string input, string newLine) + { + using (var writer = new StringWriter ()) { + using (var reader = new StringReader (input)) { + for (int i = 0; i < 9; i++) { + reader.ReadLine (); + } + string line; + while ((line = reader.ReadLine ()) != null) { + writer.Write (line); + writer.Write (newLine); + } + } + return writer.ToString (); + } + } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/AssemblyInfo.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/AssemblyInfo.cs new file mode 100644 index 00000000..13849716 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/AssemblyInfo.cs @@ -0,0 +1,37 @@ +// +// AssemblyInfo.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System.Reflection; +using System.Runtime.CompilerServices; +using System; + +[assembly: AssemblyTitle("Mono.TextTemplating")] +[assembly: AssemblyDescription("An implementation of Visual Studio's T4 text templating")] +[assembly: AssemblyCompany("The Mono Project")] +[assembly: AssemblyProduct("MonoDevelop")] +[assembly: AssemblyCopyright("MIT/X11")] +[assembly: CLSCompliant (true)] + +//[assembly: AssemblyVersion("1.0.0.0")] diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/ChangeLog b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/ChangeLog new file mode 100644 index 00000000..51377760 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/ChangeLog @@ -0,0 +1,212 @@ +2010-03-15 Michael Hutchinson + + * Mono.TextTemplating/TemplateGenerator.cs: Expose OutputFile + for custom tool to access. + +2010-03-01 Michael Hutchinson + + * Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs: A + handler for AssemblyResolve events that looks them up in the + domain that created the resolver. + + * Makefile.am: + * Mono.TextTemplating.csproj: Added file. + +2009-11-27 Olivier Dagenais + * Mono.TextTemplating/ParsedTemplate.cs: Fixed a bug where the + location of an error was being ignored. + +2009-11-27 Olivier Dagenais + + * Mono.TextTemplating/TemplatingEngine.cs: Mark the generated + type as partial. + +2009-11-25 Michael Hutchinson + + * Mono.TextTemplating/ParsedTemplate.cs: Don't check if + included file exists before trying to resolve it from the + host, because host may use include paths. Patch from Aaron + Bockover. + +2009-08-17 Michael Hutchinson + + * Mono.TextTemplating/TemplatingEngine.cs: Fix NRE when + template fails to compile. + +2009-08-12 Michael Hutchinson + + * Makefile.am: + * Mono.TextTemplating.csproj: Include the ASP.NET MVC and + TextTemplating addins in the main solution and build. + +2009-08-11 Michael Hutchinson + + * Mono.TextTemplating.csproj: + * Mono.TextTemplating/ParsedTemplate.cs: + * Mono.TextTemplating/CompiledTemplate.cs: + * Mono.TextTemplating/TemplatingEngine.cs: + * Mono.TextTemplating/TemplateGenerator.cs: + * Mono.TextTemplating/IExtendedTextTemplatingEngineHost.cs: + Add support for caching compiled templates, and a couple of + bugfixes. Patch from Nathan Baulch + (nathan.baulch@gmail.com). + +2009-06-25 Michael Hutchinson + + * Mono.TextTemplating/TemplatingEngine.cs: Handle expressions + and content in helpers, based on patch from Nathan Baulch. + Liberally add C# 3 sugar to neaten up CodeDOM usage. + +2009-06-25 Michael Hutchinson + + * Mono.TextTemplating/TemplateGenerator.cs: Added overload for + Process template that uses input/output strings directly, + avoiding file read/write. Expose engine to subclasses. + + * Mono.TextTemplating/Tokeniser.cs: Remove outdated TODO. + +2009-04-13 Michael Hutchinson + + * Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs: Use + IConvertible.ToString (formatProvider) when possible. + + Thanks to Stuart Carnie for this patch. + +2009-04-13 Michael Hutchinson + + * Mono.TextTemplating/Tokeniser.cs: Add support for Mac and + Windows newlines. + + * Mono.TextTemplating/TemplatingEngine.cs: Keep temp files + when in debug mode, so that the generated code can be + debugged. + + * Mono.TextTemplating/ParsedTemplate.cs: Fixes for csc + compilation. + + Thanks to Stuart Carnie for this patch. + +2009-04-03 Michael Hutchinson + + * Mono.TextTemplating.csproj: + * Mono.TextTemplating/TemplatingEngine.cs: + * Mono.TextTemplating/TemplateSettings.cs: + * Microsoft.VisualStudio.TextTemplating/Engine.cs: Move the + real engine into the Mono.TextTemplating namespace and + expose helper methods so that they can be tested. + +2009-03-13 Michael Hutchinson + + * Mono.TextTemplating.csproj: Move output dir from ../bin to + ../build. + +2009-03-12 Michael Hutchinson + + * Mono.TextTemplating/Tokeniser.cs: Tweaked location of next + state after directive. + +2009-03-12 Michael Hutchinson + + * Mono.TextTemplating/Tokeniser.cs: Location tweaks within + directives. + + * Mono.TextTemplating/ParsedTemplate.cs: Make Location + equatable. + +2009-03-10 Michael Hutchinson + + * Mono.TextTemplating/Tokeniser.cs: + * Mono.TextTemplating/ParsedTemplate.cs: Fix end location + capture after newline handling changes. + +2009-03-10 Michael Hutchinson + + * Mono.TextTemplating/Tokeniser.cs: + * Microsoft.VisualStudio.TextTemplating/Engine.cs: Match T4's + newline handling. + +2009-03-10 Michael Hutchinson + + * Mono.TextTemplating/ParsedTemplate.cs: Fix logic that + prevented adding directives. + +2009-03-09 Michael Hutchinson + + * Mono.TextTemplating/Tokeniser.cs: + * Mono.TextTemplating/ParsedTemplate.cs: More accurate + location captures. Capture start of tags as well as start of + content. + +2009-03-09 Michael Hutchinson + + * Mono.TextTemplating/TemplateGenerator.cs: Report exceptions + in errors. + + * Mono.TextTemplating/Tokeniser.cs: Make API public. + + * Mono.TextTemplating/ParsedTemplate.cs: Unify segment types. + Track end locations. Make API public. Allow parsing without + includes. + + * Microsoft.VisualStudio.TextTemplating/Engine.cs: Track + location API. + +2009-03-06 Michael Hutchinson + + * Mono.TextTemplating/TemplateGenerator.cs: Fix + SetFileExtension. + + * Microsoft.VisualStudio.TextTemplating/Engine.cs: Capture + hostspecific attribute from template directive. + +2009-03-05 Michael Hutchinson + + * Mono.TextTemplating/TemplateGenerator.cs: Fix output + extension changing. + + * Mono.TextTemplating/Tokeniser.cs: Fix helper regions. + +2009-03-05 Michael Hutchinson + + * Mono.TextTemplating.csproj: Updated. + + * Mono.TextTemplating/TemplateGenerator.cs: Simple template + host implementation. Doesn't handle everything yet. + + * Mono.TextTemplating/Tokeniser.cs: Fix a number of offset + issues that broke most captures. Only allow EOF in content + regions, and in this case capture the last content. Track + current column, for error reporting. + + * Mono.TextTemplating/ParsedTemplate.cs: Overhaul location + tracking for error reporting. Don't record empty segments. + + * Microsoft.VisualStudio.TextTemplating/Engine.cs: Use run + method instead of runner, since the whole thing's done in + the appdomain now. Catch errors from the runner. Use host's + default assemblies and imports. Track ParsedTemplate error + reporting changes. Filter out content regions with only a + single newline. + + * Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs: + Don't cache delegates; this won't work for instances. Maybe + IL generation is called for. + +2009-03-04 Michael Hutchinson + + * AssemblyInfo.cs: + * Mono.TextTemplating: + * Mono.TextTemplating.csproj: + * Mono.TextTemplating/Tokeniser.cs: + * Microsoft.VisualStudio.TextTemplating: + * Mono.TextTemplating/ParsedTemplate.cs: + * Microsoft.VisualStudio.TextTemplating/Engine.cs: + * Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs: + * Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs: + * Microsoft.VisualStudio.TextTemplating/TextTransformation.cs: + * Microsoft.VisualStudio.TextTemplating/ITextTemplatingEngineHost.cs: + * Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs: + * Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs: + Move T4 implementation to its own assembly. Tweak some + appdomain stuff. + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Makefile.am b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Makefile.am new file mode 100644 index 00000000..72ec1552 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Makefile.am @@ -0,0 +1,55 @@ +ADDIN_BUILD = $(top_builddir)/build/AddIns/MonoDevelop.TextTemplating +ASSEMBLY = $(ADDIN_BUILD)/Mono.TextTemplating.dll + +DEPS = + +REFS = \ + -r:System \ + -r:System.Core + +FILES = \ + AssemblyInfo.cs \ + Microsoft.VisualStudio.TextTemplating/AssemblyCacheMonitor.cs \ + Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs \ + Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs \ + Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs \ + Microsoft.VisualStudio.TextTemplating/Engine.cs \ + Microsoft.VisualStudio.TextTemplating/Interfaces.cs \ + Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs \ + Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs \ + Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs \ + Microsoft.VisualStudio.TextTemplating/TextTransformation.cs \ + Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs \ + Mono.TextTemplating/CompiledTemplate.cs \ + Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs \ + Mono.TextTemplating/ParsedTemplate.cs \ + Mono.TextTemplating/TemplateGenerator.cs \ + Mono.TextTemplating/TemplateSettings.cs \ + Mono.TextTemplating/TemplatingEngine.cs \ + Mono.TextTemplating/Tokeniser.cs + +RES = + +all: $(ASSEMBLY) $(ASSEMBLY).mdb $(DATA_FILE_BUILD) + +$(ASSEMBLY): $(build_sources) $(build_resources) $(DEPS) + mkdir -p $(ADDIN_BUILD) + $(CSC) $(CSC_FLAGS) -debug -out:$@ -target:library $(REFS) $(build_deps) \ + $(build_resources:%=/resource:%) $(build_sources) + +$(ASSEMBLY).mdb: $(ASSEMBLY) + +$(DATA_FILE_BUILD): $(srcdir)$(subst $(ADDIN_BUILD),, $@) + mkdir -p $(ADDIN_BUILD)/Schemas + cp $(srcdir)/$(subst $(ADDIN_BUILD),,$@) $@ + +check: all + +assemblydir = $(MD_ADDIN_DIR)/MonoDevelop.TextTemplating +assembly_DATA = $(ASSEMBLY) $(ASSEMBLY).mdb + +CLEANFILES = $(ASSEMBLY) $(ASSEMBLY).mdb +EXTRA_DIST = $(FILES) $(RES) + +include $(top_srcdir)/Makefile.include + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/AssemblyCacheMonitor.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/AssemblyCacheMonitor.cs new file mode 100644 index 00000000..68a17fb0 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/AssemblyCacheMonitor.cs @@ -0,0 +1,43 @@ +// +// AssemblyCacheMonitor.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2010 Novell, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; + +namespace Microsoft.VisualStudio.TextTemplating +{ + public sealed class AssemblyCacheMonitor : MarshalByRefObject + { + public AssemblyCacheMonitor () + { + } + + public int GetStaleAssembliesCount (TimeSpan assemblyStaleTime) + { + throw new NotImplementedException (); + } + } +} + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs new file mode 100644 index 00000000..f86dbd2e --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs @@ -0,0 +1,63 @@ +// +// DirectiveProcessor.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; + +namespace Microsoft.VisualStudio.TextTemplating +{ + public abstract class DirectiveProcessor + { + protected DirectiveProcessor () + { + } + + public virtual void Initialize (ITextTemplatingEngineHost host) + { + if (host == null) + throw new ArgumentNullException ("host"); + } + + public virtual void StartProcessingRun (CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors) + { + if (languageProvider == null) + throw new ArgumentNullException ("languageProvider"); + this.Errors = errors; + } + + public abstract void FinishProcessingRun (); + public abstract string GetClassCodeForProcessingRun (); + public abstract string[] GetImportsForProcessingRun (); + public abstract string GetPostInitializationCodeForProcessingRun (); + public abstract string GetPreInitializationCodeForProcessingRun (); + public abstract string[] GetReferencesForProcessingRun (); + public abstract bool IsDirectiveSupported (string directiveName); + public abstract void ProcessDirective (string directiveName, IDictionary arguments); + + protected CompilerErrorCollection Errors { get; private set; } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs new file mode 100644 index 00000000..1d95faca --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs @@ -0,0 +1,56 @@ +// +// DirectiveProcessorException.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Runtime.Serialization; + +namespace Microsoft.VisualStudio.TextTemplating +{ + + [Serializable] + public class DirectiveProcessorException : Exception + { + + public DirectiveProcessorException () + { + } + + public DirectiveProcessorException (string message) + : base (message) + { + } + + public DirectiveProcessorException (SerializationInfo info, StreamingContext context) + : base (info, context) + { + } + + public DirectiveProcessorException (string message, Exception inner) + : base (message, inner) + { + } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs new file mode 100644 index 00000000..9934646b --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs @@ -0,0 +1,40 @@ +// +// EncodingHelper.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2010 Novell, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Text; + +namespace Microsoft.VisualStudio.TextTemplating +{ + public static class EncodingHelper + { + public static Encoding GetEncoding (string filePath) + { + throw new NotImplementedException (); + } + } +} + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Engine.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Engine.cs new file mode 100644 index 00000000..fc9c9aac --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Engine.cs @@ -0,0 +1,58 @@ +// +// Engine.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.IO; +using System.Text; +using System.Collections.Generic; +using System.CodeDom; +using System.CodeDom.Compiler; +using Mono.TextTemplating; + +namespace Microsoft.VisualStudio.TextTemplating +{ + public class Engine : ITextTemplatingEngine + { + TemplatingEngine engine = new TemplatingEngine (); + + public Engine () + { + } + + public string ProcessTemplate (string content, ITextTemplatingEngineHost host) + { + return engine.ProcessTemplate (content, host); + } + + public string PreprocessTemplate (string content, ITextTemplatingEngineHost host, string className, + string classNamespace, out string language, out string[] references) + { + return engine.PreprocessTemplate (content, host, className, classNamespace, out language, out references); + } + + public const string CacheAssembliesOptionString = "CacheAssemblies"; + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Interfaces.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Interfaces.cs new file mode 100644 index 00000000..5ea7413f --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Interfaces.cs @@ -0,0 +1,84 @@ +// +// ITextTemplatingEngineHost.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009-2010 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Text; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections; +using System.Runtime.Serialization; + +namespace Microsoft.VisualStudio.TextTemplating +{ + public interface IRecognizeHostSpecific + { + void SetProcessingRunIsHostSpecific (bool hostSpecific); + bool RequiresProcessingRunIsHostSpecific { get; } + } + + [CLSCompliant(true)] + public interface ITextTemplatingEngine + { + string ProcessTemplate (string content, ITextTemplatingEngineHost host); + string PreprocessTemplate (string content, ITextTemplatingEngineHost host, string className, + string classNamespace, out string language, out string[] references); + } + + [CLSCompliant(true)] + public interface ITextTemplatingEngineHost + { + object GetHostOption (string optionName); + bool LoadIncludeText (string requestFileName, out string content, out string location); + void LogErrors (CompilerErrorCollection errors); + AppDomain ProvideTemplatingAppDomain (string content); + string ResolveAssemblyReference (string assemblyReference); + Type ResolveDirectiveProcessor (string processorName); + string ResolveParameterValue (string directiveId, string processorName, string parameterName); + string ResolvePath (string path); + void SetFileExtension (string extension); + void SetOutputEncoding (Encoding encoding, bool fromOutputDirective); + IList StandardAssemblyReferences { get; } + IList StandardImports { get; } + string TemplateFile { get; } + } + + [CLSCompliant(true)] + public interface ITextTemplatingSession : + IEquatable, IEquatable, IDictionary, + ICollection>, + IEnumerable>, + IEnumerable, ISerializable + { + Guid Id { get; } + } + + [CLSCompliant(true)] + public interface ITextTemplatingSessionHost + { + ITextTemplatingSession CreateSession (); + ITextTemplatingSession Session { get; set; } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs new file mode 100644 index 00000000..9518a428 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs @@ -0,0 +1,268 @@ +// +// ParameterDirectiveProcessor.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2010 Novell, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.CodeDom; +using System.IO; +using System.Linq; +using System.Reflection; + +namespace Microsoft.VisualStudio.TextTemplating +{ + public sealed class ParameterDirectiveProcessor : DirectiveProcessor, IRecognizeHostSpecific + { + CodeDomProvider provider; + bool isCSharp; + bool useMonoHack; + + bool hostSpecific; + List postStatements = new List (); + CodeTypeMemberCollection members = new CodeTypeMemberCollection (); + + public ParameterDirectiveProcessor () + { + } + + public override void StartProcessingRun (CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors) + { + base.StartProcessingRun (languageProvider, templateContents, errors); + this.provider = languageProvider; + //HACK: Mono as of 2.10.2 doesn't implement GenerateCodeFromMember + if (Type.GetType ("Mono.Runtime") != null) + useMonoHack = true; + if (languageProvider is Microsoft.CSharp.CSharpCodeProvider) + isCSharp = true; + postStatements.Clear (); + members.Clear (); + } + + public override void FinishProcessingRun () + { + var statement = new CodeConditionStatement ( + new CodeBinaryOperatorExpression ( + new CodePropertyReferenceExpression ( + new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Errors"), "HasErrors"), + CodeBinaryOperatorType.ValueEquality, + new CodePrimitiveExpression (false)), + postStatements.ToArray ()); + + postStatements.Clear (); + postStatements.Add (statement); + } + + public override string GetClassCodeForProcessingRun () + { + var options = new CodeGeneratorOptions (); + using (var sw = new StringWriter ()) { + GenerateCodeFromMembers (sw, options); + return Indent (sw.ToString (), " "); + } + } + + string Indent (string s, string indent) + { + if (isCSharp) + return Mono.TextTemplating.TemplatingEngine.IndentSnippetText (s, indent); + return s; + } + + public override string[] GetImportsForProcessingRun () + { + return null; + } + + public override string GetPostInitializationCodeForProcessingRun () + { + return Indent (StatementsToCode (postStatements), " "); + } + + public override string GetPreInitializationCodeForProcessingRun () + { + return null; + } + + string StatementsToCode (List statements) + { + var options = new CodeGeneratorOptions (); + using (var sw = new StringWriter ()) { + foreach (var statement in statements) + provider.GenerateCodeFromStatement (statement, sw, options); + return sw.ToString (); + } + } + + public override string[] GetReferencesForProcessingRun () + { + return null; + } + + public override bool IsDirectiveSupported (string directiveName) + { + return directiveName == "parameter"; + } + + public override void ProcessDirective (string directiveName, IDictionary arguments) + { + string name = arguments["name"]; + string type = arguments["type"]; + if (string.IsNullOrEmpty (name)) + throw new DirectiveProcessorException ("Parameter directive has no name argument"); + if (string.IsNullOrEmpty (type)) + throw new DirectiveProcessorException ("Parameter directive has no type argument"); + + string fieldName = "_" + name + "Field"; + var typeRef = new CodeTypeReference (type); + var thisRef = new CodeThisReferenceExpression (); + var fieldRef = new CodeFieldReferenceExpression (thisRef, fieldName); + + var property = new CodeMemberProperty () { + Name = name, + Attributes = MemberAttributes.Public | MemberAttributes.Final, + HasGet = true, + HasSet = false, + Type = typeRef + }; + property.GetStatements.Add (new CodeMethodReturnStatement (fieldRef)); + members.Add (new CodeMemberField (typeRef, fieldName)); + members.Add (property); + + string acquiredName = "_" + name + "Acquired"; + var valRef = new CodeVariableReferenceExpression ("data"); + var namePrimitive = new CodePrimitiveExpression (name); + var sessionRef = new CodePropertyReferenceExpression (thisRef, "Session"); + var callContextTypeRefExpr = new CodeTypeReferenceExpression ("System.Runtime.Remoting.Messaging.CallContext"); + var nullPrim = new CodePrimitiveExpression (null); + + var acquiredVariable = new CodeVariableDeclarationStatement (typeof (bool), acquiredName, new CodePrimitiveExpression (false)); + var acquiredVariableRef = new CodeVariableReferenceExpression (acquiredVariable.Name); + this.postStatements.Add (acquiredVariable); + + //checks the local called "data" can be cast and assigned to the field, and if successful, sets acquiredVariable to true + var checkCastThenAssignVal = new CodeConditionStatement ( + new CodeMethodInvokeExpression ( + new CodeTypeOfExpression (typeRef), "IsAssignableFrom", new CodeMethodInvokeExpression (valRef, "GetType")), + new CodeStatement[] { + new CodeAssignStatement (fieldRef, new CodeCastExpression (typeRef, valRef)), + new CodeAssignStatement (acquiredVariableRef, new CodePrimitiveExpression (true)), + }, + new CodeStatement[] { + new CodeExpressionStatement (new CodeMethodInvokeExpression (thisRef, "Error", + new CodePrimitiveExpression ("The type '" + type + "' of the parameter '" + name + + "' did not match the type passed to the template"))), + }); + + //tries to gets the value from the session + var checkSession = new CodeConditionStatement ( + new CodeBinaryOperatorExpression (NotNull (sessionRef), CodeBinaryOperatorType.BooleanAnd, + new CodeMethodInvokeExpression (sessionRef, "ContainsKey", namePrimitive)), + new CodeVariableDeclarationStatement (typeof (object), "data", new CodeIndexerExpression (sessionRef, namePrimitive)), + checkCastThenAssignVal); + + this.postStatements.Add (checkSession); + + //if acquiredVariable is false, tries to gets the value from the host + if (hostSpecific) { + var hostRef = new CodePropertyReferenceExpression (thisRef, "Host"); + var checkHost = new CodeConditionStatement ( + BooleanAnd (IsFalse (acquiredVariableRef), NotNull (hostRef)), + new CodeVariableDeclarationStatement (typeof (string), "data", + new CodeMethodInvokeExpression (hostRef, "ResolveParameterValue", nullPrim, nullPrim, namePrimitive)), + new CodeConditionStatement (NotNull (valRef), checkCastThenAssignVal)); + + this.postStatements.Add (checkHost); + } + + //if acquiredVariable is false, tries to gets the value from the call context + var checkCallContext = new CodeConditionStatement ( + IsFalse (acquiredVariableRef), + new CodeVariableDeclarationStatement (typeof (object), "data", + new CodeMethodInvokeExpression (callContextTypeRefExpr, "LogicalGetData", namePrimitive)), + new CodeConditionStatement (NotNull (valRef), checkCastThenAssignVal)); + + this.postStatements.Add (checkCallContext); + } + + static CodeBinaryOperatorExpression NotNull (CodeExpression reference) + { + return new CodeBinaryOperatorExpression (reference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null)); + } + + static CodeBinaryOperatorExpression IsFalse (CodeExpression expr) + { + return new CodeBinaryOperatorExpression (expr, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (false)); + } + + static CodeBinaryOperatorExpression BooleanAnd (CodeExpression expr1, CodeExpression expr2) + { + return new CodeBinaryOperatorExpression (expr1, CodeBinaryOperatorType.BooleanAnd, expr2); + } + + void IRecognizeHostSpecific.SetProcessingRunIsHostSpecific (bool hostSpecific) + { + this.hostSpecific = hostSpecific; + } + + public bool RequiresProcessingRunIsHostSpecific { + get { return false; } + } + + void GenerateCodeFromMembers (StringWriter sw, CodeGeneratorOptions options) + { + if (!useMonoHack) { + foreach (CodeTypeMember member in members) + provider.GenerateCodeFromMember (member, sw, options); + } + + var cgType = typeof (CodeGenerator); + var cgInit = cgType.GetMethod ("InitOutput", BindingFlags.NonPublic | BindingFlags.Instance); + var cgFieldGen = cgType.GetMethod ("GenerateField", BindingFlags.NonPublic | BindingFlags.Instance); + var cgPropGen = cgType.GetMethod ("GenerateProperty", BindingFlags.NonPublic | BindingFlags.Instance); + +#pragma warning disable 0618 + var generator = (CodeGenerator) provider.CreateGenerator (); +#pragma warning restore 0618 + var dummy = new CodeTypeDeclaration ("Foo"); + + foreach (CodeTypeMember member in members) { + var f = member as CodeMemberField; + if (f != null) { + cgInit.Invoke (generator, new object[] { sw, options }); + cgFieldGen.Invoke (generator, new object[] { f }); + continue; + } + var p = member as CodeMemberProperty; + if (p != null) { + cgInit.Invoke (generator, new object[] { sw, options }); + cgPropGen.Invoke (generator, new object[] { p, dummy }); + continue; + } + } + } + } +} + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs new file mode 100644 index 00000000..bb48357c --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs @@ -0,0 +1,196 @@ +// +// RequiresProvidesDirectiveProcessor.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.Text; + +namespace Microsoft.VisualStudio.TextTemplating +{ + + + public abstract class RequiresProvidesDirectiveProcessor : DirectiveProcessor + { + bool isInProcessingRun; + ITextTemplatingEngineHost host; + StringBuilder preInitBuffer = new StringBuilder (); + StringBuilder postInitBuffer = new StringBuilder (); + StringBuilder codeBuffer = new StringBuilder (); + CodeDomProvider languageProvider; + + protected RequiresProvidesDirectiveProcessor () + { + } + + public override void Initialize (ITextTemplatingEngineHost host) + { + base.Initialize (host); + this.host = host; + } + + protected abstract void InitializeProvidesDictionary (string directiveName, IDictionary providesDictionary); + protected abstract void InitializeRequiresDictionary (string directiveName, IDictionary requiresDictionary); + protected abstract string FriendlyName { get; } + + protected abstract void GeneratePostInitializationCode (string directiveName, StringBuilder codeBuffer, CodeDomProvider languageProvider, + IDictionary requiresArguments, IDictionary providesArguments); + protected abstract void GeneratePreInitializationCode (string directiveName, StringBuilder codeBuffer, CodeDomProvider languageProvider, + IDictionary requiresArguments, IDictionary providesArguments); + protected abstract void GenerateTransformCode (string directiveName, StringBuilder codeBuffer, CodeDomProvider languageProvider, + IDictionary requiresArguments, IDictionary providesArguments); + + protected virtual void PostProcessArguments (string directiveName, IDictionary requiresArguments, + IDictionary providesArguments) + { + } + + public override string GetClassCodeForProcessingRun () + { + AssertNotProcessing (); + return codeBuffer.ToString (); + } + + public override string[] GetImportsForProcessingRun () + { + AssertNotProcessing (); + return null; + } + + public override string[] GetReferencesForProcessingRun () + { + AssertNotProcessing (); + return null; + } + + public override string GetPostInitializationCodeForProcessingRun () + { + AssertNotProcessing (); + return postInitBuffer.ToString (); + } + + public override string GetPreInitializationCodeForProcessingRun () + { + AssertNotProcessing (); + return preInitBuffer.ToString (); + } + + public override void StartProcessingRun (CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors) + { + AssertNotProcessing (); + isInProcessingRun = true; + base.StartProcessingRun (languageProvider, templateContents, errors); + + this.languageProvider = languageProvider; + codeBuffer.Length = 0; + preInitBuffer.Length = 0; + postInitBuffer.Length = 0; + } + + public override void FinishProcessingRun () + { + isInProcessingRun = false; + } + + void AssertNotProcessing () + { + if (isInProcessingRun) + throw new InvalidOperationException (); + } + + //FIXME: handle escaping + IEnumerable> ParseArgs (string args) + { + var pairs = args.Split (';'); + foreach (var p in pairs) { + int eq = p.IndexOf ('='); + var k = p.Substring (0, eq); + var v = p.Substring (eq); + yield return new KeyValuePair (k, v); + } + } + + public override void ProcessDirective (string directiveName, IDictionary arguments) + { + if (directiveName == null) + throw new ArgumentNullException ("directiveName"); + if (arguments == null) + throw new ArgumentNullException ("arguments"); + + var providesDictionary = new Dictionary (); + var requiresDictionary = new Dictionary (); + + string provides; + if (arguments.TryGetValue ("provides", out provides)) { + foreach (var arg in ParseArgs (provides)) { + providesDictionary.Add (arg.Key, arg.Value); + } + } + + string requires; + if (arguments.TryGetValue ("requires", out requires)) { + foreach (var arg in ParseArgs (requires)) { + requiresDictionary.Add (arg.Key, arg.Value); + } + } + + InitializeRequiresDictionary (directiveName, requiresDictionary); + InitializeProvidesDictionary (directiveName, providesDictionary); + + var id = ProvideUniqueId (directiveName, arguments, requiresDictionary, providesDictionary); + + foreach (var req in requiresDictionary) { + var val = host.ResolveParameterValue (id, FriendlyName, req.Key); + if (val != null) + requiresDictionary[req.Key] = val; + else if (req.Value == null) + throw new DirectiveProcessorException ("Could not resolve required value '" + req.Key + "'"); + } + + foreach (var req in providesDictionary) { + var val = host.ResolveParameterValue (id, FriendlyName, req.Key); + if (val != null) + providesDictionary[req.Key] = val; + } + + PostProcessArguments (directiveName, requiresDictionary, providesDictionary); + + GeneratePreInitializationCode (directiveName, preInitBuffer, languageProvider, requiresDictionary, providesDictionary); + GeneratePostInitializationCode (directiveName, postInitBuffer, languageProvider, requiresDictionary, providesDictionary); + GenerateTransformCode (directiveName, codeBuffer, languageProvider, requiresDictionary, providesDictionary); + } + + protected virtual string ProvideUniqueId (string directiveName, IDictionary arguments, + IDictionary requiresArguments, IDictionary providesArguments) + { + return directiveName; + } + + protected ITextTemplatingEngineHost Host { + get { return host; } + } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs new file mode 100644 index 00000000..b29dbd01 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs @@ -0,0 +1,71 @@ +// +// TextTemplatingSession.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2010 Novell, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using System.Collections.Generic; +using System.Collections; +using System.Runtime.Serialization; + +namespace Microsoft.VisualStudio.TextTemplating +{ + [Serializable] + public sealed class TextTemplatingSession : Dictionary, ITextTemplatingSession + { + public TextTemplatingSession () : this (Guid.NewGuid ()) + { + } + + public TextTemplatingSession (Guid id) + { + this.Id = id; + } + + public Guid Id { + get; private set; + } + + public override int GetHashCode () + { + return Id.GetHashCode (); + } + + public override bool Equals (object obj) + { + var o = obj as TextTemplatingSession; + return o != null && o.Equals (this); + } + + public bool Equals (Guid other) + { + return other.Equals (Id); + } + + public bool Equals (ITextTemplatingSession other) + { + return other != null && other.Id == this.Id; + } + } +} + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs new file mode 100644 index 00000000..409a36a9 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs @@ -0,0 +1,219 @@ +// +// TextTransformation.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Text; + +namespace Microsoft.VisualStudio.TextTemplating +{ + public abstract class TextTransformation : IDisposable + { + Stack indents; + string currentIndent = string.Empty; + CompilerErrorCollection errors; + StringBuilder builder; + bool endsWithNewline; + + public TextTransformation () + { + } + + protected internal virtual void Initialize () + { + } + + public abstract string TransformText (); + + public virtual IDictionary Session { get; set; } + + #region Errors + + public void Error (string message) + { + Errors.Add (new CompilerError (null, -1, -1, null, message)); + } + + public void Warning (string message) + { + var err = new CompilerError (null, -1, -1, null, message) { + IsWarning = true, + }; + Errors.Add (err); + } + + protected internal CompilerErrorCollection Errors { + get { + if (errors == null) + errors = new CompilerErrorCollection (); + return errors; + } + } + + Stack Indents { + get { + if (indents == null) + indents = new Stack (); + return indents; + } + } + + #endregion + + #region Indents + + public string PopIndent () + { + if (Indents.Count == 0) + return ""; + int lastPos = currentIndent.Length - Indents.Pop (); + string last = currentIndent.Substring (lastPos); + currentIndent = currentIndent.Substring (0, lastPos); + return last; + } + + public void PushIndent (string indent) + { + if (indent == null) + throw new ArgumentNullException ("indent"); + Indents.Push (indent.Length); + currentIndent += indent; + } + + public void ClearIndent () + { + currentIndent = string.Empty; + Indents.Clear (); + } + + public string CurrentIndent { + get { return currentIndent; } + } + + #endregion + + #region Writing + + protected StringBuilder GenerationEnvironment { + get { + if (builder == null) + builder = new StringBuilder (); + return builder; + } + set { + builder = value; + } + } + + public void Write (string textToAppend) + { + if (string.IsNullOrEmpty (textToAppend)) + return; + + if ((GenerationEnvironment.Length == 0 || endsWithNewline) && CurrentIndent.Length > 0) { + GenerationEnvironment.Append (CurrentIndent); + } + endsWithNewline = false; + + char last = textToAppend[textToAppend.Length-1]; + if (last == '\n' || last == '\r') { + endsWithNewline = true; + } + + if (CurrentIndent.Length == 0) { + GenerationEnvironment.Append (textToAppend); + return; + } + + //insert CurrentIndent after every newline (\n, \r, \r\n) + //but if there's one at the end of the string, ignore it, it'll be handled next time thanks to endsWithNewline + int lastNewline = 0; + for (int i = 0; i < textToAppend.Length - 1; i++) { + char c = textToAppend[i]; + if (c == '\r') { + if (textToAppend[i + 1] == '\n') { + i++; + if (i == textToAppend.Length - 1) + break; + } + } else if (c != '\n') { + continue; + } + i++; + int len = i - lastNewline; + if (len > 0) { + GenerationEnvironment.Append (textToAppend, lastNewline, i - lastNewline); + } + GenerationEnvironment.Append (CurrentIndent); + lastNewline = i; + } + if (lastNewline > 0) + GenerationEnvironment.Append (textToAppend, lastNewline, textToAppend.Length - lastNewline); + else + GenerationEnvironment.Append (textToAppend); + } + + public void Write (string format, params object[] args) + { + Write (string.Format (format, args)); + } + + public void WriteLine (string textToAppend) + { + Write (textToAppend); + GenerationEnvironment.AppendLine (); + endsWithNewline = true; + } + + public void WriteLine (string format, params object[] args) + { + WriteLine (string.Format (format, args)); + } + + #endregion + + #region Dispose + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + protected virtual void Dispose (bool disposing) + { + } + + ~TextTransformation () + { + Dispose (false); + } + + #endregion + + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs new file mode 100644 index 00000000..7f5934e2 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs @@ -0,0 +1,69 @@ +// +// ToStringHelper.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace Microsoft.VisualStudio.TextTemplating +{ + public static class ToStringHelper + { + static object [] formatProviderAsParameterArray; + + static IFormatProvider formatProvider = System.Globalization.CultureInfo.InvariantCulture; + + static ToStringHelper () + { + formatProviderAsParameterArray = new object[] { formatProvider }; + } + + public static string ToStringWithCulture (object objectToConvert) + { + if (objectToConvert == null) + throw new ArgumentNullException ("objectToConvert"); + + IConvertible conv = objectToConvert as IConvertible; + if (conv != null) + return conv.ToString (formatProvider); + + var str = objectToConvert as string; + if (str != null) + return str; + + //TODO: implement a cache of types and DynamicMethods + MethodInfo mi = objectToConvert.GetType ().GetMethod ("ToString", new Type[] { typeof (IFormatProvider) }); + if (mi != null) + return (string) mi.Invoke (objectToConvert, formatProviderAsParameterArray); + return objectToConvert.ToString (); + } + + public static IFormatProvider FormatProvider { + get { return (IFormatProvider)formatProviderAsParameterArray[0]; } + set { formatProviderAsParameterArray[0] = formatProvider = value; } + } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating.csproj b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating.csproj new file mode 100644 index 00000000..2523f46b --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating.csproj @@ -0,0 +1,79 @@ + + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {A2364D6A-00EF-417C-80A6-815726C70032} + Library + Mono.TextTemplating + Mono.TextTemplating + + + true + full + false + ..\bin + DEBUG + prompt + 4 + false + + + none + false + ..\bin + prompt + 4 + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CompiledTemplate.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CompiledTemplate.cs new file mode 100644 index 00000000..3e2f9458 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CompiledTemplate.cs @@ -0,0 +1,113 @@ +// +// CompiledTemplate.cs +// +// Author: +// Nathan Baulch +// +// Copyright (c) 2009 Nathan Baulch +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Reflection; +using Microsoft.VisualStudio.TextTemplating; +using System.CodeDom.Compiler; +using System.Globalization; + +namespace Mono.TextTemplating +{ + public sealed class CompiledTemplate : MarshalByRefObject, IDisposable + { + ITextTemplatingEngineHost host; + TextTransformation tt; + CultureInfo culture; + string[] assemblyFiles; + + public CompiledTemplate (ITextTemplatingEngineHost host, CompilerResults results, string fullName, CultureInfo culture, + string[] assemblyFiles) + { + AppDomain.CurrentDomain.AssemblyResolve += ResolveReferencedAssemblies; + this.host = host; + this.culture = culture; + this.assemblyFiles = assemblyFiles; + Load (results, fullName); + } + + void Load (CompilerResults results, string fullName) + { + var assembly = results.CompiledAssembly; + Type transformType = assembly.GetType (fullName); + tt = (TextTransformation) Activator.CreateInstance (transformType); + + //set the host property if it exists + var hostProp = transformType.GetProperty ("Host", typeof (ITextTemplatingEngineHost)); + if (hostProp != null && hostProp.CanWrite) + hostProp.SetValue (tt, host, null); + + var sessionHost = host as ITextTemplatingSessionHost; + if (sessionHost != null) { + //FIXME: should we create a session if it's null? + tt.Session = sessionHost.Session; + } + } + + public string Process () + { + tt.Errors.Clear (); + + //set the culture + if (culture != null) + ToStringHelper.FormatProvider = culture; + else + ToStringHelper.FormatProvider = CultureInfo.InvariantCulture; + + tt.Initialize (); + + string output = null; + try { + output = tt.TransformText (); + } catch (Exception ex) { + tt.Error ("Error running transform: " + ex.ToString ()); + } + host.LogErrors (tt.Errors); + + ToStringHelper.FormatProvider = CultureInfo.InvariantCulture; + return output; + } + + System.Reflection.Assembly ResolveReferencedAssemblies (object sender, ResolveEventArgs args) + { + System.Reflection.Assembly asm = null; + foreach (var asmFile in assemblyFiles) { + var name = System.IO.Path.GetFileNameWithoutExtension (asmFile); + if (args.Name.StartsWith (name)) + asm = System.Reflection.Assembly.LoadFrom (asmFile); + } + return asm; + } + + public void Dispose () + { + if (host != null) { + host = null; + AppDomain.CurrentDomain.AssemblyResolve -= ResolveReferencedAssemblies; + } + } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs new file mode 100644 index 00000000..593ed734 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs @@ -0,0 +1,59 @@ +// +// CrossAppDomainAssemblyResolver.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2010 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; + +namespace Mono.TextTemplating +{ + [Serializable] + /// + /// Provides a handler for AssemblyResolve events that looks them up in the domain that created the resolver. + /// + public class CrossAppDomainAssemblyResolver + { + ParentDomainLookup parent = new ParentDomainLookup (); + + public System.Reflection.Assembly Resolve (object sender, ResolveEventArgs args) + { + var location = parent.GetAssemblyPath (args.Name); + if (location != null) + return System.Reflection.Assembly.LoadFrom (location); + return null; + } + + class ParentDomainLookup : MarshalByRefObject + { + public string GetAssemblyPath (string name) + { + var assem = System.Reflection.Assembly.Load (name); + if (assem != null) + return assem.Location; + return null; + } + } + } +} + diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/ParsedTemplate.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/ParsedTemplate.cs new file mode 100644 index 00000000..f3ba0ae0 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/ParsedTemplate.cs @@ -0,0 +1,320 @@ +// +// Template.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.IO; +using Microsoft.VisualStudio.TextTemplating; + +namespace Mono.TextTemplating +{ + + + public class ParsedTemplate + { + List segments = new List (); + CompilerErrorCollection errors = new CompilerErrorCollection (); + string rootFileName; + + public ParsedTemplate (string rootFileName) + { + this.rootFileName = rootFileName; + } + + public List RawSegments { + get { return segments; } + } + + public IEnumerable Directives { + get { + foreach (ISegment seg in segments) { + Directive dir = seg as Directive; + if (dir != null) + yield return dir; + } + } + } + + public IEnumerable Content { + get { + foreach (ISegment seg in segments) { + TemplateSegment ts = seg as TemplateSegment; + if (ts != null) + yield return ts; + } + } + } + + public CompilerErrorCollection Errors { + get { return errors; } + } + + public static ParsedTemplate FromText (string content, ITextTemplatingEngineHost host) + { + ParsedTemplate template = new ParsedTemplate (host.TemplateFile); + try { + template.Parse (host, new Tokeniser (host.TemplateFile, content)); + } catch (ParserException ex) { + template.LogError (ex.Message, ex.Location); + } + return template; + } + + public void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser) + { + Parse (host, tokeniser, true); + } + + public void ParseWithoutIncludes (Tokeniser tokeniser) + { + Parse (null, tokeniser, false); + } + + void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser, bool parseIncludes) + { + bool skip = false; + while ((skip || tokeniser.Advance ()) && tokeniser.State != State.EOF) { + skip = false; + ISegment seg = null; + switch (tokeniser.State) { + case State.Block: + if (!String.IsNullOrEmpty (tokeniser.Value)) + seg = new TemplateSegment (SegmentType.Block, tokeniser.Value, tokeniser.Location); + break; + case State.Content: + if (!String.IsNullOrEmpty (tokeniser.Value)) + seg = new TemplateSegment (SegmentType.Content, tokeniser.Value, tokeniser.Location); + break; + case State.Expression: + if (!String.IsNullOrEmpty (tokeniser.Value)) + seg = new TemplateSegment (SegmentType.Expression, tokeniser.Value, tokeniser.Location); + break; + case State.Helper: + if (!String.IsNullOrEmpty (tokeniser.Value)) + seg = new TemplateSegment (SegmentType.Helper, tokeniser.Value, tokeniser.Location); + break; + case State.Directive: + Directive directive = null; + string attName = null; + while (!skip && tokeniser.Advance ()) { + switch (tokeniser.State) { + case State.DirectiveName: + if (directive == null) { + directive = new Directive (tokeniser.Value.ToLower (), tokeniser.Location); + directive.TagStartLocation = tokeniser.TagStartLocation; + if (!parseIncludes || directive.Name != "include") + segments.Add (directive); + } else + attName = tokeniser.Value; + break; + case State.DirectiveValue: + if (attName != null && directive != null) + directive.Attributes[attName.ToLower ()] = tokeniser.Value; + else + LogError ("Directive value without name", tokeniser.Location); + attName = null; + break; + case State.Directive: + if (directive != null) + directive.EndLocation = tokeniser.TagEndLocation; + break; + default: + skip = true; + break; + } + } + if (parseIncludes && directive.Name == "include") + Import (host, directive, Path.GetDirectoryName (tokeniser.Location.FileName)); + break; + default: + throw new InvalidOperationException (); + } + if (seg != null) { + seg.TagStartLocation = tokeniser.TagStartLocation; + seg.EndLocation = tokeniser.TagEndLocation; + segments.Add (seg); + } + } + } + + void Import (ITextTemplatingEngineHost host, Directive includeDirective, string relativeToDirectory) + { + string fileName; + if (includeDirective.Attributes.Count > 1 || !includeDirective.Attributes.TryGetValue ("file", out fileName)) { + LogError ("Unexpected attributes in include directive", includeDirective.StartLocation); + return; + } + + //try to resolve path relative to the file that included it + if (!Path.IsPathRooted (fileName)) { + string possible = Path.Combine (relativeToDirectory, fileName); + if (File.Exists (possible)) + fileName = possible; + } + + string content, resolvedName; + if (host.LoadIncludeText (fileName, out content, out resolvedName)) + Parse (host, new Tokeniser (resolvedName, content), true); + else + LogError ("Could not resolve include file '" + fileName + "'.", includeDirective.StartLocation); + } + + void LogError (string message, Location location, bool isWarning) + { + CompilerError err = new CompilerError (); + err.ErrorText = message; + if (location.FileName != null) { + err.Line = location.Line; + err.Column = location.Column; + err.FileName = location.FileName ?? string.Empty; + } else { + err.FileName = rootFileName ?? string.Empty; + } + err.IsWarning = isWarning; + errors.Add (err); + } + + public void LogError (string message) + { + LogError (message, Location.Empty, false); + } + + public void LogWarning (string message) + { + LogError (message, Location.Empty, true); + } + + public void LogError (string message, Location location) + { + LogError (message, location, false); + } + + public void LogWarning (string message, Location location) + { + LogError (message, location, true); + } + } + + public interface ISegment + { + Location StartLocation { get; } + Location EndLocation { get; set; } + Location TagStartLocation {get; set; } + } + + public class TemplateSegment : ISegment + { + public TemplateSegment (SegmentType type, string text, Location start) + { + this.Type = type; + this.StartLocation = start; + this.Text = text; + } + + public SegmentType Type { get; private set; } + public string Text { get; private set; } + public Location TagStartLocation { get; set; } + public Location StartLocation { get; private set; } + public Location EndLocation { get; set; } + } + + public class Directive : ISegment + { + public Directive (string name, Location start) + { + this.Name = name; + this.Attributes = new Dictionary (); + this.StartLocation = start; + } + + public string Name { get; private set; } + public Dictionary Attributes { get; private set; } + public Location TagStartLocation { get; set; } + public Location StartLocation { get; private set; } + public Location EndLocation { get; set; } + + public string Extract (string key) + { + string value; + if (!Attributes.TryGetValue (key, out value)) + return null; + Attributes.Remove (key); + return value; + } + } + + public enum SegmentType + { + Block, + Expression, + Content, + Helper + } + + public struct Location : IEquatable + { + public Location (string fileName, int line, int column) : this() + { + FileName = fileName; + Column = column; + Line = line; + } + + public int Line { get; private set; } + public int Column { get; private set; } + public string FileName { get; private set; } + + public static Location Empty { + get { return new Location (null, -1, -1); } + } + + public Location AddLine () + { + return new Location (this.FileName, this.Line + 1, 1); + } + + public Location AddCol () + { + return AddCols (1); + } + + public Location AddCols (int number) + { + return new Location (this.FileName, this.Line, this.Column + number); + } + + public override string ToString () + { + return string.Format("[{0} ({1},{2})]", FileName, Line, Column); + } + + public bool Equals (Location other) + { + return other.Line == Line && other.Column == Column && other.FileName == FileName; + } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateGenerator.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateGenerator.cs new file mode 100644 index 00000000..dd752857 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateGenerator.cs @@ -0,0 +1,373 @@ +// +// TemplatingHost.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.CodeDom.Compiler; +using System.IO; +using System.Text; +using Microsoft.VisualStudio.TextTemplating; + +namespace Mono.TextTemplating +{ + public class TemplateGenerator : MarshalByRefObject, ITextTemplatingEngineHost + { + //re-usable + TemplatingEngine engine; + + //per-run variables + string inputFile, outputFile; + Encoding encoding; + + //host fields + CompilerErrorCollection errors = new CompilerErrorCollection (); + List refs = new List (); + List imports = new List (); + List includePaths = new List (); + List referencePaths = new List (); + + //host properties for consumers to access + public CompilerErrorCollection Errors { get { return errors; } } + public List Refs { get { return refs; } } + public List Imports { get { return imports; } } + public List IncludePaths { get { return includePaths; } } + public List ReferencePaths { get { return referencePaths; } } + public string OutputFile { get { return outputFile; } } + + public TemplateGenerator () + { + Refs.Add (typeof (TextTransformation).Assembly.Location); + Refs.Add (typeof(System.Uri).Assembly.Location); + Imports.Add ("System"); + } + + public CompiledTemplate CompileTemplate (string content) + { + if (String.IsNullOrEmpty (content)) + throw new ArgumentNullException ("content"); + + errors.Clear (); + encoding = Encoding.UTF8; + + return Engine.CompileTemplate (content, this); + } + + protected TemplatingEngine Engine { + get { + if (engine == null) + engine = new TemplatingEngine (); + return engine; + } + } + + public bool ProcessTemplate (string inputFile, string outputFile) + { + if (String.IsNullOrEmpty (inputFile)) + throw new ArgumentNullException ("inputFile"); + if (String.IsNullOrEmpty (outputFile)) + throw new ArgumentNullException ("outputFile"); + + string content; + try { + content = File.ReadAllText (inputFile); + } catch (IOException ex) { + errors.Clear (); + AddError ("Could not read input file '" + inputFile + "':\n" + ex.ToString ()); + return false; + } + + string output; + ProcessTemplate (inputFile, content, ref outputFile, out output); + + try { + if (!errors.HasErrors) + File.WriteAllText (outputFile, output, encoding); + } catch (IOException ex) { + AddError ("Could not write output file '" + outputFile + "':\n" + ex.ToString ()); + } + + return !errors.HasErrors; + } + + public bool ProcessTemplate (string inputFileName, string inputContent, ref string outputFileName, out string outputContent) + { + errors.Clear (); + encoding = Encoding.UTF8; + + this.outputFile = outputFileName; + this.inputFile = inputFileName; + outputContent = Engine.ProcessTemplate (inputContent, this); + outputFileName = this.outputFile; + + return !errors.HasErrors; + } + + public bool PreprocessTemplate (string inputFile, string className, string classNamespace, + string outputFile, System.Text.Encoding encoding, out string language, out string[] references) + { + language = null; + references = null; + + if (string.IsNullOrEmpty (inputFile)) + throw new ArgumentNullException ("inputFile"); + if (string.IsNullOrEmpty (outputFile)) + throw new ArgumentNullException ("outputFile"); + + string content; + try { + content = File.ReadAllText (inputFile); + } catch (IOException ex) { + errors.Clear (); + AddError ("Could not read input file '" + inputFile + "':\n" + ex.ToString ()); + return false; + } + + string output; + PreprocessTemplate (inputFile, className, classNamespace, content, out language, out references, out output); + + try { + if (!errors.HasErrors) + File.WriteAllText (outputFile, output, encoding); + } catch (IOException ex) { + AddError ("Could not write output file '" + outputFile + "':\n" + ex.ToString ()); + } + + return !errors.HasErrors; + } + + public bool PreprocessTemplate (string inputFileName, string className, string classNamespace, string inputContent, + out string language, out string[] references, out string outputContent) + { + errors.Clear (); + encoding = Encoding.UTF8; + + this.inputFile = inputFileName; + outputContent = Engine.PreprocessTemplate (inputContent, this, className, classNamespace, out language, out references); + + return !errors.HasErrors; + } + + CompilerError AddError (string error) + { + CompilerError err = new CompilerError (); + err.ErrorText = error; + Errors.Add (err); + return err; + } + + #region Virtual members + + public virtual object GetHostOption (string optionName) + { + return null; + } + + public virtual AppDomain ProvideTemplatingAppDomain (string content) + { + return null; + } + + //FIXME: implement + protected virtual string ResolveAssemblyReference (string assemblyReference) + { + //foreach (string referencePath in ReferencePaths) { + // + //} + return assemblyReference; + } + + protected virtual string ResolveParameterValue (string directiveId, string processorName, string parameterName) + { + var key = new ParameterKey (processorName, directiveId, parameterName); + string value; + if (parameters.TryGetValue (key, out value)) + return value; + if (processorName != null || directiveId != null) + return ResolveParameterValue (null, null, parameterName); + return null; + } + + protected virtual Type ResolveDirectiveProcessor (string processorName) + { + KeyValuePair value; + if (!directiveProcessors.TryGetValue (processorName, out value)) + throw new Exception (string.Format ("No directive processor registered as '{0}'", processorName)); + var asmPath = ResolveAssemblyReference (value.Value); + if (asmPath == null) + throw new Exception (string.Format ("Could not resolve assembly '{0}' for directive processor '{1}'", value.Value, processorName)); + var asm = System.Reflection.Assembly.LoadFrom (asmPath); + return asm.GetType (value.Key, true); + } + + protected virtual string ResolvePath (string path) + { + path = System.Environment.ExpandEnvironmentVariables (path); + if (Path.IsPathRooted (path)) + return path; + var dir = Path.GetDirectoryName (inputFile); + var test = Path.Combine (dir, path); + if (File.Exists (test)) + return test; + return null; + } + + #endregion + + Dictionary parameters = new Dictionary (); + Dictionary> directiveProcessors = new Dictionary> (); + + public void AddDirectiveProcessor (string name, string klass, string assembly) + { + directiveProcessors.Add (name, new KeyValuePair (klass,assembly)); + } + + public void AddParameter (string processorName, string directiveName, string parameterName, string value) + { + parameters.Add (new ParameterKey (processorName, directiveName, parameterName), value); + } + + protected virtual bool LoadIncludeText (string requestFileName, out string content, out string location) + { + content = ""; + location = ResolvePath (requestFileName); + + if (location == null) { + foreach (string path in includePaths) { + string f = Path.Combine (path, requestFileName); + if (File.Exists (f)) { + location = f; + break; + } + } + } + + if (location == null) + return false; + + try { + content = File.ReadAllText (location); + return true; + } catch (IOException ex) { + AddError ("Could not read included file '" + location + "':\n" + ex.ToString ()); + } + return false; + } + + #region Explicit ITextTemplatingEngineHost implementation + + bool ITextTemplatingEngineHost.LoadIncludeText (string requestFileName, out string content, out string location) + { + return LoadIncludeText (requestFileName, out content, out location); + } + + void ITextTemplatingEngineHost.LogErrors (CompilerErrorCollection errors) + { + this.errors.AddRange (errors); + } + + string ITextTemplatingEngineHost.ResolveAssemblyReference (string assemblyReference) + { + return ResolveAssemblyReference (assemblyReference); + } + + string ITextTemplatingEngineHost.ResolveParameterValue (string directiveId, string processorName, string parameterName) + { + return ResolveParameterValue (directiveId, processorName, parameterName); + } + + Type ITextTemplatingEngineHost.ResolveDirectiveProcessor (string processorName) + { + return ResolveDirectiveProcessor (processorName); + } + + string ITextTemplatingEngineHost.ResolvePath (string path) + { + return ResolvePath (path); + } + + void ITextTemplatingEngineHost.SetFileExtension (string extension) + { + extension = extension.TrimStart ('.'); + if (Path.HasExtension (outputFile)) { + outputFile = Path.ChangeExtension (outputFile, extension); + } else { + outputFile = outputFile + "." + extension; + } + } + + void ITextTemplatingEngineHost.SetOutputEncoding (System.Text.Encoding encoding, bool fromOutputDirective) + { + this.encoding = encoding; + } + + IList ITextTemplatingEngineHost.StandardAssemblyReferences { + get { return refs; } + } + + IList ITextTemplatingEngineHost.StandardImports { + get { return imports; } + } + + string ITextTemplatingEngineHost.TemplateFile { + get { return inputFile; } + } + + #endregion + + struct ParameterKey : IEquatable + { + public ParameterKey (string processorName, string directiveName, string parameterName) + { + this.processorName = processorName ?? ""; + this.directiveName = directiveName ?? ""; + this.parameterName = parameterName ?? ""; + unchecked { + hashCode = this.processorName.GetHashCode () + ^ this.directiveName.GetHashCode () + ^ this.parameterName.GetHashCode (); + } + } + + string processorName, directiveName, parameterName; + int hashCode; + + public override bool Equals (object obj) + { + return obj != null && obj is ParameterKey && Equals ((ParameterKey)obj); + } + + public bool Equals (ParameterKey other) + { + return processorName == other.processorName && directiveName == other.directiveName && parameterName == other.parameterName; + } + + public override int GetHashCode () + { + return hashCode; + } + } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateSettings.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateSettings.cs new file mode 100644 index 00000000..8221c65e --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateSettings.cs @@ -0,0 +1,75 @@ +// +// TemplateSettings.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.Text; +using System.Collections.Generic; +using Microsoft.VisualStudio.TextTemplating; + +namespace Mono.TextTemplating +{ + + public class TemplateSettings + { + public TemplateSettings () + { + Imports = new HashSet (); + Assemblies = new HashSet (); + CustomDirectives = new List (); + DirectiveProcessors = new Dictionary (); + } + + public bool HostSpecific { get; set; } + public bool Debug { get; set; } + public string Inherits { get; set; } + public string Name { get; set; } + public string Namespace { get; set; } + public HashSet Imports { get; private set; } + public HashSet Assemblies { get; private set; } + public System.CodeDom.Compiler.CodeDomProvider Provider { get; set; } + public string Language { get; set; } + public string CompilerOptions { get; set; } + public Encoding Encoding { get; set; } + public string Extension { get; set; } + public System.Globalization.CultureInfo Culture { get; set; } + public List CustomDirectives { get; private set; } + public Dictionary DirectiveProcessors { get; private set; } + public bool IncludePreprocessingHelpers { get; set; } + public bool IsPreprocessed { get; set; } + } + + public class CustomDirective + { + public CustomDirective (string processorName, Directive directive) + { + this.ProcessorName = processorName; + this.Directive = directive; + } + + public string ProcessorName { get; set; } + public Directive Directive { get; set; } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs new file mode 100644 index 00000000..5878adce --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs @@ -0,0 +1,963 @@ +// +// Engine.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.IO; +using System.Text; +using System.Collections.Generic; +using System.CodeDom; +using System.CodeDom.Compiler; +using Microsoft.CSharp; +using Microsoft.VisualStudio.TextTemplating; +using System.Linq; +using System.Reflection; + +namespace Mono.TextTemplating +{ + public class TemplatingEngine : MarshalByRefObject, Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngine + { + public string ProcessTemplate (string content, ITextTemplatingEngineHost host) + { + var tpl = CompileTemplate (content, host); + try { + if (tpl != null) + return tpl.Process (); + return null; + } finally { + if (tpl != null) + tpl.Dispose (); + } + } + + public string PreprocessTemplate (string content, ITextTemplatingEngineHost host, string className, + string classNamespace, out string language, out string[] references) + { + if (content == null) + throw new ArgumentNullException ("content"); + if (host == null) + throw new ArgumentNullException ("host"); + if (className == null) + throw new ArgumentNullException ("className"); + if (classNamespace == null) + throw new ArgumentNullException ("classNamespace"); + + language = null; + references = null; + + var pt = ParsedTemplate.FromText (content, host); + if (pt.Errors.HasErrors) { + host.LogErrors (pt.Errors); + return null; + } + + var settings = GetSettings (host, pt); + if (pt.Errors.HasErrors) { + host.LogErrors (pt.Errors); + return null; + } + settings.Name = className; + settings.Namespace = classNamespace; + settings.IncludePreprocessingHelpers = string.IsNullOrEmpty (settings.Inherits); + settings.IsPreprocessed = true; + language = settings.Language; + + var ccu = GenerateCompileUnit (host, content, pt, settings); + references = ProcessReferences (host, pt, settings).ToArray (); + + host.LogErrors (pt.Errors); + if (pt.Errors.HasErrors) { + return null; + } + + var options = new CodeGeneratorOptions (); + using (var sw = new StringWriter ()) { + settings.Provider.GenerateCodeFromCompileUnit (ccu, sw, options); + return sw.ToString (); + }; + } + + public CompiledTemplate CompileTemplate (string content, ITextTemplatingEngineHost host) + { + if (content == null) + throw new ArgumentNullException ("content"); + if (host == null) + throw new ArgumentNullException ("host"); + + var pt = ParsedTemplate.FromText (content, host); + if (pt.Errors.HasErrors) { + host.LogErrors (pt.Errors); + return null; + } + + var settings = GetSettings (host, pt); + if (pt.Errors.HasErrors) { + host.LogErrors (pt.Errors); + return null; + } + + if (!string.IsNullOrEmpty (settings.Extension)) { + host.SetFileExtension (settings.Extension); + } + if (settings.Encoding != null) { + //FIXME: when is this called with false? + host.SetOutputEncoding (settings.Encoding, true); + } + + var ccu = GenerateCompileUnit (host, content, pt, settings); + var references = ProcessReferences (host, pt, settings); + if (pt.Errors.HasErrors) { + host.LogErrors (pt.Errors); + return null; + } + + var results = GenerateCode (host, references, settings, ccu); + if (results.Errors.HasErrors) { + host.LogErrors (pt.Errors); + host.LogErrors (results.Errors); + return null; + } + + var templateClassFullName = settings.Namespace + "." + settings.Name; + var domain = host.ProvideTemplatingAppDomain (content); + if (domain != null) { + var type = typeof (CompiledTemplate); + var obj = domain.CreateInstanceAndUnwrap (type.Assembly.FullName, type.FullName, false, + BindingFlags.CreateInstance, null, + new object[] { host, results, templateClassFullName, settings.Culture, references.ToArray () }, + null, null); + return (CompiledTemplate) obj; + } else { + return new CompiledTemplate (host, results, templateClassFullName, settings.Culture, references.ToArray ()); + } + } + + static CompilerResults GenerateCode (ITextTemplatingEngineHost host, IEnumerable references, TemplateSettings settings, CodeCompileUnit ccu) + { + var pars = new CompilerParameters () { + GenerateExecutable = false, + CompilerOptions = settings.CompilerOptions, + IncludeDebugInformation = settings.Debug, + GenerateInMemory = false, + }; + + foreach (var r in references) + pars.ReferencedAssemblies.Add (r); + + if (settings.Debug) + pars.TempFiles.KeepFiles = true; + + return settings.Provider.CompileAssemblyFromDom (pars, ccu); + } + + static HashSet ProcessReferences (ITextTemplatingEngineHost host, ParsedTemplate pt, TemplateSettings settings) + { + var resolved = new HashSet (); + + foreach (string assem in settings.Assemblies.Union (host.StandardAssemblyReferences)) { + if (resolved.Contains (assem)) + continue; + + string resolvedAssem = host.ResolveAssemblyReference (assem); + if (!string.IsNullOrEmpty (resolvedAssem)) { + resolved.Add (resolvedAssem); + } else { + pt.LogError ("Could not resolve assembly reference '" + assem + "'"); + return null; + } + } + return resolved; + } + + public static TemplateSettings GetSettings (ITextTemplatingEngineHost host, ParsedTemplate pt) + { + var settings = new TemplateSettings (); + + foreach (Directive dt in pt.Directives) { + switch (dt.Name) { + case "template": + string val = dt.Extract ("language"); + if (val != null) + settings.Language = val; + val = dt.Extract ("debug"); + if (val != null) + settings.Debug = string.Compare (val, "true", StringComparison.OrdinalIgnoreCase) == 0; + val = dt.Extract ("inherits"); + if (val != null) + settings.Inherits = val; + val = dt.Extract ("culture"); + if (val != null) { + System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.GetCultureInfo (val); + if (culture == null) + pt.LogWarning ("Could not find culture '" + val + "'", dt.StartLocation); + else + settings.Culture = culture; + } + val = dt.Extract ("hostspecific"); + if (val != null) { + settings.HostSpecific = string.Compare (val, "true", StringComparison.OrdinalIgnoreCase) == 0; + } + val = dt.Extract ("CompilerOptions"); + if (val != null) { + settings.CompilerOptions = val; + } + break; + + case "assembly": + string name = dt.Extract ("name"); + if (name == null) + pt.LogError ("Missing name attribute in assembly directive", dt.StartLocation); + else + settings.Assemblies.Add (name); + break; + + case "import": + string namespac = dt.Extract ("namespace"); + if (namespac == null) + pt.LogError ("Missing namespace attribute in import directive", dt.StartLocation); + else + settings.Imports.Add (namespac); + break; + + case "output": + settings.Extension = dt.Extract ("extension"); + string encoding = dt.Extract ("encoding"); + if (encoding != null) + settings.Encoding = Encoding.GetEncoding (encoding); + break; + + case "include": + throw new InvalidOperationException ("Include is handled in the parser"); + + case "parameter": + AddDirective (settings, host, "ParameterDirectiveProcessor", dt); + continue; + + default: + string processorName = dt.Extract ("Processor"); + if (processorName == null) + throw new InvalidOperationException ("Custom directive '" + dt.Name + "' does not specify a processor"); + + AddDirective (settings, host, processorName, dt); + continue; + } + ComplainExcessAttributes (dt, pt); + } + + //initialize the custom processors + foreach (var kv in settings.DirectiveProcessors) { + kv.Value.Initialize (host); + var hs = kv.Value as IRecognizeHostSpecific; + if (hs == null) + continue; + if (hs.RequiresProcessingRunIsHostSpecific && !settings.HostSpecific) { + settings.HostSpecific = true; + pt.LogWarning ("Directive processor '" + kv.Key + "' requires hostspecific=true, forcing on."); + } + hs.SetProcessingRunIsHostSpecific (settings.HostSpecific); + } + + if (settings.Name == null) + settings.Name = string.Format ("GeneratedTextTransformation{0:x}", new System.Random ().Next ()); + if (settings.Namespace == null) + settings.Namespace = typeof (TextTransformation).Namespace; + + //resolve the CodeDOM provider + if (String.IsNullOrEmpty (settings.Language)) { + pt.LogError ("No language was specified for the template"); + return settings; + } + + if (settings.Language == "C#v3.5") { + Dictionary providerOptions = new Dictionary (); + providerOptions.Add ("CompilerVersion", "v3.5"); + settings.Provider = new CSharpCodeProvider (providerOptions); + } + else { + settings.Provider = CodeDomProvider.CreateProvider (settings.Language); + } + + if (settings.Provider == null) { + pt.LogError ("A provider could not be found for the language '" + settings.Language + "'"); + return settings; + } + + return settings; + } + + public static string IndentSnippetText (string text, string indent) + { + var builder = new StringBuilder (text.Length); + builder.Append (indent); + int lastNewline = 0; + for (int i = 0; i < text.Length - 1; i++) { + char c = text[i]; + if (c == '\r') { + if (text[i + 1] == '\n') { + i++; + if (i == text.Length - 1) + break; + } + } else if (c != '\n') { + continue; + } + i++; + int len = i - lastNewline; + if (len > 0) { + builder.Append (text, lastNewline, i - lastNewline); + } + builder.Append (indent); + lastNewline = i; + } + if (lastNewline > 0) + builder.Append (text, lastNewline, text.Length - lastNewline); + else + builder.Append (text); + return builder.ToString (); + } + + static void AddDirective (TemplateSettings settings, ITextTemplatingEngineHost host, string processorName, Directive directive) + { + DirectiveProcessor processor; + if (!settings.DirectiveProcessors.TryGetValue (processorName, out processor)) { + switch (processorName) { + case "ParameterDirectiveProcessor": + processor = new ParameterDirectiveProcessor (); + break; + default: + Type processorType = host.ResolveDirectiveProcessor (processorName); + processor = (DirectiveProcessor) Activator.CreateInstance (processorType); + break; + } + if (!processor.IsDirectiveSupported (directive.Name)) + throw new InvalidOperationException ("Directive processor '" + processorName + "' does not support directive '" + directive.Name + "'"); + + settings.DirectiveProcessors [processorName] = processor; + } + settings.CustomDirectives.Add (new CustomDirective (processorName, directive)); + } + + static bool ComplainExcessAttributes (Directive dt, ParsedTemplate pt) + { + if (dt.Attributes.Count == 0) + return false; + StringBuilder sb = new StringBuilder ("Unknown attributes "); + bool first = true; + foreach (string key in dt.Attributes.Keys) { + if (!first) { + sb.Append (", "); + } else { + first = false; + } + sb.Append (key); + } + sb.Append (" found in "); + sb.Append (dt.Name); + sb.Append (" directive."); + pt.LogWarning (sb.ToString (), dt.StartLocation); + return false; + } + + static void ProcessDirectives (ITextTemplatingEngineHost host, string content, ParsedTemplate pt, TemplateSettings settings) + { + foreach (var processor in settings.DirectiveProcessors.Values) { + processor.StartProcessingRun (settings.Provider, content, pt.Errors); + } + + foreach (var dt in settings.CustomDirectives) { + var processor = settings.DirectiveProcessors[dt.ProcessorName]; + + if (processor is RequiresProvidesDirectiveProcessor) + throw new NotImplementedException ("RequiresProvidesDirectiveProcessor"); + + processor.ProcessDirective (dt.Directive.Name, dt.Directive.Attributes); + } + + foreach (var processor in settings.DirectiveProcessors.Values) { + processor.FinishProcessingRun (); + + var imports = processor.GetImportsForProcessingRun (); + if (imports != null) + settings.Imports.UnionWith (imports); + var references = processor.GetReferencesForProcessingRun (); + if (references != null) + settings.Assemblies.UnionWith (references); + } + } + + public static CodeCompileUnit GenerateCompileUnit (ITextTemplatingEngineHost host, string content, ParsedTemplate pt, TemplateSettings settings) + { + ProcessDirectives (host, content, pt, settings); + + //prep the compile unit + var ccu = new CodeCompileUnit (); + var namespac = new CodeNamespace (settings.Namespace); + ccu.Namespaces.Add (namespac); + + foreach (string ns in settings.Imports.Union (host.StandardImports)) + namespac.Imports.Add (new CodeNamespaceImport (ns)); + + //prep the type + var type = new CodeTypeDeclaration (settings.Name); + type.IsPartial = true; + if (!string.IsNullOrEmpty (settings.Inherits)) { + type.BaseTypes.Add (new CodeTypeReference (settings.Inherits)); + } else if (!settings.IncludePreprocessingHelpers) { + type.BaseTypes.Add (TypeRef ()); + } else { + type.BaseTypes.Add (new CodeTypeReference (settings.Name + "Base")); + } + namespac.Types.Add (type); + + //prep the transform method + var transformMeth = new CodeMemberMethod () { + Name = "TransformText", + ReturnType = new CodeTypeReference (typeof (String)), + Attributes = MemberAttributes.Public, + }; + if (!settings.IncludePreprocessingHelpers) + transformMeth.Attributes |= MemberAttributes.Override; + + transformMeth.Statements.Add (new CodeAssignStatement ( + new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "GenerationEnvironment"), + new CodePrimitiveExpression (null))); + + CodeExpression toStringHelper; + if (settings.IsPreprocessed) { + toStringHelper = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "ToStringHelper"); + } else { + toStringHelper = new CodeTypeReferenceExpression ( + new CodeTypeReference (typeof (ToStringHelper), CodeTypeReferenceOptions.GlobalReference)); + } + + //method references that will need to be used multiple times + var writeMeth = new CodeMethodReferenceExpression (new CodeThisReferenceExpression (), "Write"); + var toStringMeth = new CodeMethodReferenceExpression (toStringHelper, "ToStringWithCulture"); + bool helperMode = false; + + //build the code from the segments + foreach (TemplateSegment seg in pt.Content) { + CodeStatement st = null; + var location = new CodeLinePragma (seg.StartLocation.FileName ?? host.TemplateFile, seg.StartLocation.Line); + switch (seg.Type) { + case SegmentType.Block: + if (helperMode) + //TODO: are blocks permitted after helpers? + throw new ParserException ("Blocks are not permitted after helpers", seg.StartLocation); + st = new CodeSnippetStatement (seg.Text); + break; + case SegmentType.Expression: + st = new CodeExpressionStatement ( + new CodeMethodInvokeExpression (writeMeth, + new CodeMethodInvokeExpression (toStringMeth, new CodeSnippetExpression (seg.Text)))); + break; + case SegmentType.Content: + st = new CodeExpressionStatement (new CodeMethodInvokeExpression (writeMeth, new CodePrimitiveExpression (seg.Text))); + break; + case SegmentType.Helper: + type.Members.Add (new CodeSnippetTypeMember (seg.Text) { LinePragma = location }); + helperMode = true; + break; + default: + throw new InvalidOperationException (); + } + if (st != null) { + if (helperMode) { + //convert the statement into a snippet member and attach it to the top level type + //TODO: is there a way to do this for languages that use indentation for blocks, e.g. python? + using (var writer = new StringWriter ()) { + settings.Provider.GenerateCodeFromStatement (st, writer, null); + type.Members.Add (new CodeSnippetTypeMember (writer.ToString ()) { LinePragma = location }); + } + } else { + st.LinePragma = location; + transformMeth.Statements.Add (st); + continue; + } + } + } + + //complete the transform method + transformMeth.Statements.Add (new CodeMethodReturnStatement ( + new CodeMethodInvokeExpression ( + new CodePropertyReferenceExpression ( + new CodeThisReferenceExpression (), + "GenerationEnvironment"), + "ToString"))); + type.Members.Add (transformMeth); + + //class code from processors + foreach (var processor in settings.DirectiveProcessors.Values) { + string classCode = processor.GetClassCodeForProcessingRun (); + if (classCode != null) + type.Members.Add (new CodeSnippetTypeMember (classCode)); + } + + //generate the Host property if needed + if (settings.HostSpecific) { + GenerateHostProperty (type, settings); + } + + GenerateInitializationMethod (type, settings); + + if (settings.IncludePreprocessingHelpers) { + var baseClass = new CodeTypeDeclaration (settings.Name + "Base"); + GenerateProcessingHelpers (baseClass, settings); + AddToStringHelper (baseClass, settings); + namespac.Types.Add (baseClass); + } + return ccu; + } + + static void GenerateHostProperty (CodeTypeDeclaration type, TemplateSettings settings) + { + var hostField = new CodeMemberField (TypeRef (), "hostValue"); + hostField.Attributes = (hostField.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private; + type.Members.Add (hostField); + + var hostProp = GenerateGetterSetterProperty ("Host", hostField); + hostProp.Attributes = MemberAttributes.Public | MemberAttributes.Final; + type.Members.Add (hostProp); + } + + static void GenerateInitializationMethod (CodeTypeDeclaration type, TemplateSettings settings) + { + //initialization method + var initializeMeth = new CodeMemberMethod () { + Name = "Initialize", + ReturnType = new CodeTypeReference (typeof (void), CodeTypeReferenceOptions.GlobalReference), + Attributes = MemberAttributes.Family + }; + if (!settings.IncludePreprocessingHelpers) + initializeMeth.Attributes |= MemberAttributes.Override; + + //pre-init code from processors + foreach (var processor in settings.DirectiveProcessors.Values) { + string code = processor.GetPreInitializationCodeForProcessingRun (); + if (code != null) + initializeMeth.Statements.Add (new CodeSnippetStatement (code)); + } + + //base call + if (!settings.IncludePreprocessingHelpers) { + initializeMeth.Statements.Add ( + new CodeMethodInvokeExpression ( + new CodeMethodReferenceExpression ( + new CodeBaseReferenceExpression (), + "Initialize"))); + } + + //post-init code from processors + foreach (var processor in settings.DirectiveProcessors.Values) { + string code = processor.GetPostInitializationCodeForProcessingRun (); + if (code != null) + initializeMeth.Statements.Add (new CodeSnippetStatement (code)); + } + + type.Members.Add (initializeMeth); + } + + static void GenerateProcessingHelpers (CodeTypeDeclaration type, TemplateSettings settings) + { + var thisRef = new CodeThisReferenceExpression (); + var sbTypeRef = TypeRef (); + + var sessionField = PrivateField (TypeRef> (), "session"); + var sessionProp = GenerateGetterSetterProperty ("Session", sessionField); + sessionProp.Attributes = MemberAttributes.Public; + + var builderField = PrivateField (sbTypeRef, "builder"); + var builderFieldRef = new CodeFieldReferenceExpression (thisRef, builderField.Name); + + var generationEnvironmentProp = GenerateGetterSetterProperty ("GenerationEnvironment", builderField); + AddPropertyGetterInitializationIfFieldIsNull (generationEnvironmentProp, builderFieldRef, TypeRef ()); + + type.Members.Add (builderField); + type.Members.Add (sessionField); + type.Members.Add (sessionProp); + type.Members.Add (generationEnvironmentProp); + + AddErrorHelpers (type, settings); + AddIndentHelpers (type, settings); + AddWriteHelpers (type, settings); + } + + static void AddPropertyGetterInitializationIfFieldIsNull (CodeMemberProperty property, CodeFieldReferenceExpression fieldRef, CodeTypeReference typeRef) + { + var fieldInit = FieldInitializationIfNull (fieldRef, typeRef); + property.GetStatements.Insert (0, fieldInit); + } + + static CodeConditionStatement FieldInitializationIfNull (CodeFieldReferenceExpression fieldRef, CodeTypeReference typeRef) + { + return new CodeConditionStatement ( + new CodeBinaryOperatorExpression (fieldRef, + CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (null)), + new CodeAssignStatement (fieldRef, new CodeObjectCreateExpression (typeRef))); + } + + static void AddErrorHelpers (CodeTypeDeclaration type, TemplateSettings settings) + { + var cecTypeRef = TypeRef (); + var thisRef = new CodeThisReferenceExpression (); + var stringTypeRef = TypeRef (); + var nullPrim = new CodePrimitiveExpression (null); + var minusOnePrim = new CodePrimitiveExpression (-1); + + var errorsField = PrivateField (cecTypeRef, "errors"); + var errorsFieldRef = new CodeFieldReferenceExpression (thisRef, errorsField.Name); + + var errorsProp = GenerateGetterProperty ("Errors", errorsField); + errorsProp.Attributes = MemberAttributes.Family | MemberAttributes.Final; + errorsProp.GetStatements.Insert (0, FieldInitializationIfNull (errorsFieldRef, TypeRef())); + + var errorsPropRef = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Errors"); + + var compilerErrorTypeRef = TypeRef (); + var errorMeth = new CodeMemberMethod () { + Name = "Error", + Attributes = MemberAttributes.Public | MemberAttributes.Final, + }; + errorMeth.Parameters.Add (new CodeParameterDeclarationExpression (stringTypeRef, "message")); + errorMeth.Statements.Add (new CodeMethodInvokeExpression (errorsPropRef, "Add", + new CodeObjectCreateExpression (compilerErrorTypeRef, nullPrim, minusOnePrim, minusOnePrim, nullPrim, + new CodeArgumentReferenceExpression ("message")))); + + var warningMeth = new CodeMemberMethod () { + Name = "Warning", + Attributes = MemberAttributes.Public | MemberAttributes.Final, + }; + warningMeth.Parameters.Add (new CodeParameterDeclarationExpression (stringTypeRef, "message")); + warningMeth.Statements.Add (new CodeVariableDeclarationStatement (compilerErrorTypeRef, "val", + new CodeObjectCreateExpression (compilerErrorTypeRef, nullPrim, minusOnePrim, minusOnePrim, nullPrim, + new CodeArgumentReferenceExpression ("message")))); + warningMeth.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression ( + new CodeVariableReferenceExpression ("val"), "IsWarning"), new CodePrimitiveExpression (true))); + warningMeth.Statements.Add (new CodeMethodInvokeExpression (errorsPropRef, "Add", + new CodeVariableReferenceExpression ("val"))); + + type.Members.Add (errorsField); + type.Members.Add (errorMeth); + type.Members.Add (warningMeth); + type.Members.Add (errorsProp); + } + + static void AddIndentHelpers (CodeTypeDeclaration type, TemplateSettings settings) + { + var stringTypeRef = TypeRef (); + var thisRef = new CodeThisReferenceExpression (); + var zeroPrim = new CodePrimitiveExpression (0); + var stringEmptyRef = new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (stringTypeRef), "Empty"); + var intTypeRef = TypeRef (); + var stackIntTypeRef = TypeRef> (); + + var indentsField = PrivateField (stackIntTypeRef, "indents"); + var indentsFieldRef = new CodeFieldReferenceExpression (thisRef, indentsField.Name); + + var indentsProp = GenerateGetterProperty ("Indents", indentsField); + indentsProp.Attributes = MemberAttributes.Private; + AddPropertyGetterInitializationIfFieldIsNull (indentsProp, indentsFieldRef, TypeRef> ()); + + var indentsPropRef = new CodeFieldReferenceExpression (thisRef, indentsProp.Name); + + var currentIndentField = PrivateField (stringTypeRef, "currentIndent"); + currentIndentField.InitExpression = stringEmptyRef; + var currentIndentFieldRef = new CodeFieldReferenceExpression (thisRef, currentIndentField.Name); + + var popIndentMeth = new CodeMemberMethod () { + Name = "PopIndent", + ReturnType = stringTypeRef, + Attributes = MemberAttributes.Public | MemberAttributes.Final, + }; + popIndentMeth.Statements.Add (new CodeConditionStatement ( + new CodeBinaryOperatorExpression (new CodePropertyReferenceExpression (indentsPropRef, "Count"), + CodeBinaryOperatorType.ValueEquality, zeroPrim), + new CodeMethodReturnStatement (stringEmptyRef))); + popIndentMeth.Statements.Add (new CodeVariableDeclarationStatement (intTypeRef, "lastPos", + new CodeBinaryOperatorExpression ( + new CodePropertyReferenceExpression (currentIndentFieldRef, "Length"), + CodeBinaryOperatorType.Subtract, + new CodeMethodInvokeExpression (indentsPropRef, "Pop")))); + popIndentMeth.Statements.Add (new CodeVariableDeclarationStatement (stringTypeRef, "last", + new CodeMethodInvokeExpression (currentIndentFieldRef, "Substring", new CodeVariableReferenceExpression ("lastPos")))); + popIndentMeth.Statements.Add (new CodeAssignStatement (currentIndentFieldRef, + new CodeMethodInvokeExpression (currentIndentFieldRef, "Substring", zeroPrim, new CodeVariableReferenceExpression ("lastPos")))); + popIndentMeth.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("last"))); + + var pushIndentMeth = new CodeMemberMethod () { + Name = "PushIndent", + Attributes = MemberAttributes.Public | MemberAttributes.Final, + }; + pushIndentMeth.Parameters.Add (new CodeParameterDeclarationExpression (stringTypeRef, "indent")); + pushIndentMeth.Statements.Add (new CodeMethodInvokeExpression (indentsPropRef, "Push", + new CodePropertyReferenceExpression (new CodeArgumentReferenceExpression ("indent"), "Length"))); + pushIndentMeth.Statements.Add (new CodeAssignStatement (currentIndentFieldRef, + new CodeBinaryOperatorExpression (currentIndentFieldRef, CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("indent")))); + + var clearIndentMeth = new CodeMemberMethod () { + Name = "ClearIndent", + Attributes = MemberAttributes.Public | MemberAttributes.Final, + }; + clearIndentMeth.Statements.Add (new CodeAssignStatement (currentIndentFieldRef, stringEmptyRef)); + clearIndentMeth.Statements.Add (new CodeMethodInvokeExpression (indentsPropRef, "Clear")); + + var currentIndentProp = GenerateGetterProperty ("CurrentIndent", currentIndentField); + type.Members.Add (currentIndentField); + type.Members.Add (indentsField); + type.Members.Add (popIndentMeth); + type.Members.Add (pushIndentMeth); + type.Members.Add (clearIndentMeth); + type.Members.Add (currentIndentProp); + type.Members.Add (indentsProp); + } + + static void AddWriteHelpers (CodeTypeDeclaration type, TemplateSettings settings) + { + var stringTypeRef = TypeRef (); + var thisRef = new CodeThisReferenceExpression (); + var genEnvPropRef = new CodePropertyReferenceExpression (thisRef, "GenerationEnvironment"); + var currentIndentFieldRef = new CodeFieldReferenceExpression (thisRef, "currentIndent"); + + var textToAppendParam = new CodeParameterDeclarationExpression (stringTypeRef, "textToAppend"); + var formatParam = new CodeParameterDeclarationExpression (stringTypeRef, "format"); + var argsParam = new CodeParameterDeclarationExpression (TypeRef (), "args"); + argsParam.CustomAttributes.Add (new CodeAttributeDeclaration (TypeRef ())); + + var textToAppendParamRef = new CodeArgumentReferenceExpression ("textToAppend"); + var formatParamRef = new CodeArgumentReferenceExpression ("format"); + var argsParamRef = new CodeArgumentReferenceExpression ("args"); + + var writeMeth = new CodeMemberMethod () { + Name = "Write", + Attributes = MemberAttributes.Public | MemberAttributes.Final, + }; + writeMeth.Parameters.Add (textToAppendParam); + writeMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "Append", new CodeArgumentReferenceExpression ("textToAppend"))); + + var writeArgsMeth = new CodeMemberMethod () { + Name = "Write", + Attributes = MemberAttributes.Public | MemberAttributes.Final, + }; + writeArgsMeth.Parameters.Add (formatParam); + writeArgsMeth.Parameters.Add (argsParam); + writeArgsMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "AppendFormat", formatParamRef, argsParamRef)); + + var writeLineMeth = new CodeMemberMethod () { + Name = "WriteLine", + Attributes = MemberAttributes.Public | MemberAttributes.Final, + }; + writeLineMeth.Parameters.Add (textToAppendParam); + writeLineMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "Append", currentIndentFieldRef)); + writeLineMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "AppendLine", textToAppendParamRef)); + + var writeLineArgsMeth = new CodeMemberMethod () { + Name = "WriteLine", + Attributes = MemberAttributes.Public | MemberAttributes.Final, + }; + writeLineArgsMeth.Parameters.Add (formatParam); + writeLineArgsMeth.Parameters.Add (argsParam); + writeLineArgsMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "Append", currentIndentFieldRef)); + writeLineArgsMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "AppendFormat", formatParamRef, argsParamRef)); + writeLineArgsMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "AppendLine")); + + type.Members.Add (writeMeth); + type.Members.Add (writeArgsMeth); + type.Members.Add (writeLineMeth); + type.Members.Add (writeLineArgsMeth); + } + + static void AddToStringHelper (CodeTypeDeclaration type, TemplateSettings settings) + { + var helperCls = new CodeTypeDeclaration ("ToStringInstanceHelper") { + IsClass = true, + TypeAttributes = System.Reflection.TypeAttributes.NestedPublic, + }; + + var formatProviderField = PrivateField (TypeRef (), "formatProvider"); + formatProviderField.InitExpression = new CodePropertyReferenceExpression ( + new CodeTypeReferenceExpression (TypeRef ()), "InvariantCulture"); + var formatProviderFieldRef = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), formatProviderField.Name); + + var formatProviderProp = GenerateGetterSetterProperty ("FormatProvider", formatProviderField); + AddSetterNullCheck (formatProviderProp, formatProviderFieldRef); + + helperCls.Members.Add (formatProviderField); + helperCls.Members.Add (formatProviderProp); + + var meth = new CodeMemberMethod () { + Name = "ToStringWithCulture", + Attributes = MemberAttributes.Public | MemberAttributes.Final, + ReturnType = TypeRef (), + }; + meth.Parameters.Add (new CodeParameterDeclarationExpression (TypeRef (), "objectToConvert")); + var paramRef = new CodeArgumentReferenceExpression ("objectToConvert"); + + meth.Statements.Add (NullCheck (paramRef, paramRef.ParameterName)); + + var typeLocal = new CodeVariableDeclarationStatement (TypeRef (), "type", new CodeMethodInvokeExpression (paramRef, "GetType")); + var typeLocalRef = new CodeVariableReferenceExpression (typeLocal.Name); + meth.Statements.Add (typeLocal); + + var iConvertibleTypeLocal = new CodeVariableDeclarationStatement (TypeRef (), "iConvertibleType", + new CodeTypeOfExpression (TypeRef ())); + var iConvertibleTypeLocalRef = new CodeVariableReferenceExpression (iConvertibleTypeLocal.Name); + meth.Statements.Add (iConvertibleTypeLocal); + + meth.Statements.Add (new CodeConditionStatement ( + new CodeMethodInvokeExpression (iConvertibleTypeLocalRef, "IsAssignableFrom", typeLocalRef), + new CodeMethodReturnStatement (new CodeMethodInvokeExpression ( + new CodeCastExpression (TypeRef (), paramRef), "ToString", formatProviderFieldRef)))); + + var methInfoLocal = new CodeVariableDeclarationStatement (TypeRef (), "methInfo", + new CodeMethodInvokeExpression (typeLocalRef, "GetMethod", + new CodePrimitiveExpression ("ToString"), + new CodeArrayCreateExpression (TypeRef (), new CodeExpression [] { iConvertibleTypeLocalRef }))); + meth.Statements.Add (methInfoLocal); + var methInfoLocalRef = new CodeVariableReferenceExpression (methInfoLocal.Name); + meth.Statements.Add (new CodeConditionStatement (NotNull (methInfoLocalRef), + new CodeMethodReturnStatement (new CodeCastExpression (TypeRef (), + new CodeMethodInvokeExpression ( + methInfoLocalRef, "Invoke", paramRef, + new CodeArrayCreateExpression (TypeRef (), new CodeExpression [] { formatProviderFieldRef } )))))); + + meth.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (paramRef, "ToString"))); + + helperCls.Members.Add (meth); + + + var helperFieldName = settings.Provider.CreateValidIdentifier ("_toStringHelper"); + var helperField = PrivateField (new CodeTypeReference (helperCls.Name), helperFieldName); + helperField.InitExpression = new CodeObjectCreateExpression (helperField.Type); + type.Members.Add (helperField); + type.Members.Add (GenerateGetterProperty ("ToStringHelper", helperField)); + type.Members.Add (helperCls); + } + + #region CodeDom helpers + + static CodeTypeReference TypeRef () + { + return new CodeTypeReference (typeof (T), CodeTypeReferenceOptions.GlobalReference); + } + + static CodeMemberProperty GenerateGetterSetterProperty (string propertyName, CodeMemberField field) + { + var prop = new CodeMemberProperty () { + Name = propertyName, + Attributes = MemberAttributes.Public | MemberAttributes.Final, + Type = field.Type + }; + var fieldRef = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), field.Name); + AddGetter (prop, fieldRef); + AddSetter (prop, fieldRef); + return prop; + } + + static CodeMemberProperty GenerateGetterProperty (string propertyName, CodeMemberField field) + { + var prop = new CodeMemberProperty () { + Name = propertyName, + Attributes = MemberAttributes.Public | MemberAttributes.Final, + HasSet = false, + Type = field.Type + }; + var fieldRef = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), field.Name); + AddGetter (prop, fieldRef); + return prop; + } + + static void AddSetter (CodeMemberProperty property, CodeFieldReferenceExpression fieldRef) + { + property.HasSet = true; + property.SetStatements.Add (new CodeAssignStatement (fieldRef, new CodePropertySetValueReferenceExpression ())); + } + + static void AddGetter (CodeMemberProperty property, CodeFieldReferenceExpression fieldRef) + { + property.HasGet = true; + property.GetStatements.Add (new CodeMethodReturnStatement (fieldRef)); + } + + static void MakeGetterLazy (CodeMemberProperty property, CodeFieldReferenceExpression fieldRef, CodeExpression initExpression) + { + property.GetStatements.Insert (0, new CodeConditionStatement ( + NotNull (fieldRef), + new CodeAssignStatement (fieldRef, initExpression)) + ); + } + + static void AddSetterNullCheck (CodeMemberProperty property, CodeFieldReferenceExpression fieldRef) + { + property.SetStatements.Insert (0, NullCheck (fieldRef, fieldRef.FieldName)); + } + + static CodeStatement NullCheck (CodeExpression expr, string exceptionMessage) + { + return new CodeConditionStatement ( + IsNull (expr), + new CodeThrowExceptionStatement (new CodeObjectCreateExpression ( + new CodeTypeReference (typeof (ArgumentNullException), CodeTypeReferenceOptions.GlobalReference), + new CodePrimitiveExpression (exceptionMessage))) + ); + } + + static CodeBinaryOperatorExpression NotNull (CodeExpression reference) + { + return new CodeBinaryOperatorExpression (reference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null)); + } + + static CodeBinaryOperatorExpression IsNull (CodeExpression reference) + { + return new CodeBinaryOperatorExpression (reference, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (null)); + } + + static CodeBinaryOperatorExpression IsFalse (CodeExpression expr) + { + return new CodeBinaryOperatorExpression (expr, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (false)); + } + + static CodeBinaryOperatorExpression BooleanAnd (CodeExpression expr1, CodeExpression expr2) + { + return new CodeBinaryOperatorExpression (expr1, CodeBinaryOperatorType.BooleanAnd, expr2); + } + + static CodeStatement ArgNullCheck (CodeExpression value, params CodeExpression[] argNullExcArgs) + { + return new CodeConditionStatement ( + new CodeBinaryOperatorExpression (value, + CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (null)), + new CodeThrowExceptionStatement (new CodeObjectCreateExpression (typeof (ArgumentNullException), argNullExcArgs))); + } + + static CodeMemberField PrivateField (CodeTypeReference typeRef, string name) + { + return new CodeMemberField (typeRef, name) { + Attributes = MemberAttributes.Private + }; + } + + #endregion + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/Tokeniser.cs b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/Tokeniser.cs new file mode 100644 index 00000000..9da2d4cd --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/Tokeniser.cs @@ -0,0 +1,295 @@ +// +// Tokeniser.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.IO; +using System.Diagnostics; + +namespace Mono.TextTemplating +{ + + public class Tokeniser + { + string content; + int position = 0; + string value; + State nextState = State.Content; + Location nextStateLocation; + Location nextStateTagStartLocation; + + public Tokeniser (string fileName, string content) + { + State = State.Content; + this.content = content; + this.Location = this.nextStateLocation = this.nextStateTagStartLocation = new Location (fileName, 1, 1); + } + + public bool Advance () + { + value = null; + State = nextState; + Location = nextStateLocation; + TagStartLocation = nextStateTagStartLocation; + if (nextState == State.EOF) + return false; + nextState = GetNextStateAndCurrentValue (); + return true; + } + + State GetNextStateAndCurrentValue () + { + switch (State) { + case State.Block: + case State.Expression: + case State.Helper: + return GetBlockEnd (); + + case State.Directive: + return NextStateInDirective (); + + case State.Content: + return NextStateInContent (); + + case State.DirectiveName: + return GetDirectiveName (); + + case State.DirectiveValue: + return GetDirectiveValue (); + + default: + throw new InvalidOperationException ("Unexpected state '" + State.ToString () + "'"); + } + } + + State GetBlockEnd () + { + int start = position; + for (; position < content.Length; position++) { + char c = content[position]; + nextStateTagStartLocation = nextStateLocation; + nextStateLocation = nextStateLocation.AddCol (); + if (c == '\r') { + if (position + 1 < content.Length && content[position + 1] == '\n') + position++; + nextStateLocation = nextStateLocation.AddLine(); + } else if (c == '\n') { + nextStateLocation = nextStateLocation.AddLine(); + } else if (c =='>' && content[position-1] == '#' && content[position-2] != '\\') { + value = content.Substring (start, position - start - 1); + position++; + TagEndLocation = nextStateLocation; + + //skip newlines directly after blocks, unless they're expressions + if (State != State.Expression && (position += IsNewLine()) > 0) { + nextStateLocation = nextStateLocation.AddLine (); + } + return State.Content; + } + } + throw new ParserException ("Unexpected end of file.", nextStateLocation); + } + + State GetDirectiveName () + { + int start = position; + for (; position < content.Length; position++) { + char c = content[position]; + if (!Char.IsLetterOrDigit (c)) { + value = content.Substring (start, position - start); + return State.Directive; + } else { + nextStateLocation = nextStateLocation.AddCol (); + } + } + throw new ParserException ("Unexpected end of file.", nextStateLocation); + } + + State GetDirectiveValue () + { + int start = position; + int delimiter = '\0'; + for (; position < content.Length; position++) { + char c = content[position]; + nextStateLocation = nextStateLocation.AddCol (); + if (c == '\r') { + if (position + 1 < content.Length && content[position + 1] == '\n') + position++; + nextStateLocation = nextStateLocation.AddLine(); + } else if (c == '\n') + nextStateLocation = nextStateLocation.AddLine(); + if (delimiter == '\0') { + if (c == '\'' || c == '"') { + start = position; + delimiter = c; + } else if (!Char.IsWhiteSpace (c)) { + throw new ParserException ("Unexpected character '" + c + "'. Expecting attribute value.", nextStateLocation); + } + continue; + } + if (c == delimiter) { + value = content.Substring (start + 1, position - start - 1); + position++; + return State.Directive; + } + } + throw new ParserException ("Unexpected end of file.", nextStateLocation);; + } + + State NextStateInContent () + { + int start = position; + for (; position < content.Length; position++) { + char c = content[position]; + nextStateTagStartLocation = nextStateLocation; + nextStateLocation = nextStateLocation.AddCol (); + if (c == '\r') { + if (position + 1 < content.Length && content[position + 1] == '\n') + position++; + nextStateLocation = nextStateLocation.AddLine(); + } else if (c == '\n') { + nextStateLocation = nextStateLocation.AddLine(); + } else if (c =='<' && position + 2 < content.Length && content[position+1] == '#') { + TagEndLocation = nextStateLocation; + char type = content[position+2]; + if (type == '@') { + nextStateLocation = nextStateLocation.AddCols (2); + value = content.Substring (start, position - start); + position += 3; + return State.Directive; + } else if (type == '=') { + nextStateLocation = nextStateLocation.AddCols (2); + value = content.Substring (start, position - start); + position += 3; + return State.Expression; + } else if (type == '+') { + nextStateLocation = nextStateLocation.AddCols (2); + value = content.Substring (start, position - start); + position += 3; + return State.Helper; + } else { + value = content.Substring (start, position - start); + nextStateLocation = nextStateLocation.AddCol (); + position += 2; + return State.Block; + } + } + } + //EOF is only valid when we're in content + value = content.Substring (start); + return State.EOF; + } + + int IsNewLine() { + int found = 0; + + if (position < content.Length && content[position] == '\r') { + found++; + } + if (position+found < content.Length && content[position+found] == '\n') { + found++; + } + return found; + } + + State NextStateInDirective () { + for (; position < content.Length; position++) { + char c = content[position]; + if (c == '\r') { + if (position + 1 < content.Length && content[position + 1] == '\n') + position++; + nextStateLocation = nextStateLocation.AddLine(); + } else if (c == '\n') { + nextStateLocation = nextStateLocation.AddLine(); + } else if (Char.IsLetter (c)) { + return State.DirectiveName; + } else if (c == '=') { + nextStateLocation = nextStateLocation.AddCol (); + position++; + return State.DirectiveValue; + } else if (c == '#' && position + 1 < content.Length && content[position+1] == '>') { + position+=2; + TagEndLocation = nextStateLocation.AddCols (2); + nextStateLocation = nextStateLocation.AddCols (3); + + //skip newlines directly after directives + if ((position += IsNewLine()) > 0) { + nextStateLocation = nextStateLocation.AddLine(); + } + + return State.Content; + } else if (!Char.IsWhiteSpace (c)) { + throw new ParserException ("Directive ended unexpectedly with character '" + c + "'", nextStateLocation); + } else { + nextStateLocation = nextStateLocation.AddCol (); + } + } + throw new ParserException ("Unexpected end of file.", nextStateLocation); + } + + public State State { + get; private set; + } + + public int Position { + get { return position; } + } + + public string Content { + get { return content; } + } + + public string Value { + get { return value; } + } + + public Location Location { get; private set; } + public Location TagStartLocation { get; private set; } + public Location TagEndLocation { get; private set; } + } + + public enum State + { + Content = 0, + Directive, + Expression, + Block, + Helper, + DirectiveName, + DirectiveValue, + Name, + EOF + } + + public class ParserException : Exception + { + public ParserException (string message, Location location) : base (message) + { + Location = location; + } + + public Location Location { get; private set; } + } +} diff --git a/SparkleShare/Windows/tools/TextTemplating/README.md b/SparkleShare/Windows/tools/TextTemplating/README.md new file mode 100644 index 00000000..515765a0 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/README.md @@ -0,0 +1,19 @@ +TextTemplating +============== + +This is the TextTemplating tool inluded in MonoDevelop. +The original location of these files is +https://github.com/mono/monodevelop/tree/master/main/src/addins/TextTemplating + +Building on Windows +------------------- + +Run build.cmd or open TextTemplating.sln in visual studio 2010 +Dotnet framework 4 must be installed. + + +License +------- + +Licensed under the MIT/X11 license: http://www.opensource.org/licenses/mit-license.php + diff --git a/SparkleShare/Windows/tools/TextTemplating/TextTemplating.sln b/SparkleShare/Windows/tools/TextTemplating/TextTemplating.sln new file mode 100644 index 00000000..3de6beb6 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/TextTemplating.sln @@ -0,0 +1,26 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.TextTemplating", "Mono.TextTemplating\Mono.TextTemplating.csproj", "{A2364D6A-00EF-417C-80A6-815726C70032}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TextTransform", "TextTransform\TextTransform.csproj", "{D1D35409-C814-47F6-B038-B9B5BF0FE490}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Release|Any CPU = Release|Any CPU + Debug|Any CPU = Debug|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A2364D6A-00EF-417C-80A6-815726C70032}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A2364D6A-00EF-417C-80A6-815726C70032}.Release|Any CPU.Build.0 = Release|Any CPU + {A2364D6A-00EF-417C-80A6-815726C70032}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A2364D6A-00EF-417C-80A6-815726C70032}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D1D35409-C814-47F6-B038-B9B5BF0FE490}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D1D35409-C814-47F6-B038-B9B5BF0FE490}.Release|Any CPU.Build.0 = Release|Any CPU + {D1D35409-C814-47F6-B038-B9B5BF0FE490}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D1D35409-C814-47F6-B038-B9B5BF0FE490}.Debug|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/SparkleShare/Windows/tools/TextTemplating/TextTransform/AssemblyInfo.cs b/SparkleShare/Windows/tools/TextTemplating/TextTransform/AssemblyInfo.cs new file mode 100644 index 00000000..abe1e8b4 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/TextTransform/AssemblyInfo.cs @@ -0,0 +1,39 @@ +// +// AssemblyInfo.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System.Reflection; +using System.Runtime.CompilerServices; + +// Information about this assembly is defined by the following attributes. +// Change them to the values specific to your project. + +[assembly: AssemblyTitle("TextTransform")] +[assembly: AssemblyDescription("T4 text transformation tool")] +[assembly: AssemblyCompany("The Mono Project")] +[assembly: AssemblyProduct("MonoDevelop")] +[assembly: AssemblyCopyright("MIT/X11")] + +//[assembly: AssemblyVersion("1.0.0.0")] + diff --git a/SparkleShare/Windows/tools/TextTemplating/TextTransform/ChangeLog b/SparkleShare/Windows/tools/TextTemplating/TextTransform/ChangeLog new file mode 100644 index 00000000..08db48ec --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/TextTransform/ChangeLog @@ -0,0 +1,25 @@ +2009-08-12 Michael Hutchinson + + * Makefile.am: + * TextTransform.csproj: Include the ASP.NET MVC and + TextTemplating addins in the main solution and build. + +2009-03-13 Michael Hutchinson + + * TextTransform.csproj: Move output dir from ../bin to + ../build. + +2009-03-05 Michael Hutchinson + + * TextTransform.csproj: Updated. + + * TextTransform.cs: Complete the runner implementation. + +2009-03-04 Michael Hutchinson + + * Options.cs: + * AssemblyInfo.cs: + * TextTransform.cs: + * TextTransform.csproj: Stub out the command-line + TextTransform tool. + diff --git a/SparkleShare/Windows/tools/TextTemplating/TextTransform/Makefile.am b/SparkleShare/Windows/tools/TextTemplating/TextTransform/Makefile.am new file mode 100644 index 00000000..bd472254 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/TextTransform/Makefile.am @@ -0,0 +1,35 @@ +ADDIN_BUILD = $(top_builddir)/build/AddIns/MonoDevelop.TextTemplating +ASSEMBLY = $(ADDIN_BUILD)/TextTransform.exe + +DEPS = $(top_builddir)/build/AddIns/MonoDevelop.TextTemplating/Mono.TextTemplating.dll + +REFS = \ + -r:System \ + -r:System.Core + +FILES = \ + AssemblyInfo.cs \ + Options.cs \ + TextTransform.cs + +RES = + +all: $(ASSEMBLY) $(ASSEMBLY).mdb $(DATA_FILE_BUILD) + +$(ASSEMBLY): $(build_sources) $(build_resources) $(DEPS) + mkdir -p $(ADDIN_BUILD) + $(CSC) $(CSC_FLAGS) -debug -out:$@ -target:exe $(REFS) $(build_deps) \ + $(build_resources:%=/resource:%) $(build_sources) + +$(ASSEMBLY).mdb: $(ASSEMBLY) + +check: all + +assemblydir = $(MD_ADDIN_DIR)/MonoDevelop.TextTemplating +assembly_DATA = $(ASSEMBLY) $(ASSEMBLY).mdb + +CLEANFILES = $(ASSEMBLY) $(ASSEMBLY).mdb +EXTRA_DIST = $(FILES) $(RES) + +include $(top_srcdir)/Makefile.include + diff --git a/SparkleShare/Windows/tools/TextTemplating/TextTransform/Options.cs b/SparkleShare/Windows/tools/TextTemplating/TextTransform/Options.cs new file mode 100644 index 00000000..a64ea4d4 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/TextTransform/Options.cs @@ -0,0 +1,1112 @@ +// +// Options.cs +// +// Authors: +// Jonathan Pryor +// +// Copyright (C) 2008 Novell (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +// Compile With: +// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll +// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll +// +// The LINQ version just changes the implementation of +// OptionSet.Parse(IEnumerable), and confers no semantic changes. + +// +// A Getopt::Long-inspired option parsing library for C#. +// +// NDesk.Options.OptionSet is built upon a key/value table, where the +// key is a option format string and the value is a delegate that is +// invoked when the format string is matched. +// +// Option format strings: +// Regex-like BNF Grammar: +// name: .+ +// type: [=:] +// sep: ( [^{}]+ | '{' .+ '}' )? +// aliases: ( name type sep ) ( '|' name type sep )* +// +// Each '|'-delimited name is an alias for the associated action. If the +// format string ends in a '=', it has a required value. If the format +// string ends in a ':', it has an optional value. If neither '=' or ':' +// is present, no value is supported. `=' or `:' need only be defined on one +// alias, but if they are provided on more than one they must be consistent. +// +// Each alias portion may also end with a "key/value separator", which is used +// to split option values if the option accepts > 1 value. If not specified, +// it defaults to '=' and ':'. If specified, it can be any character except +// '{' and '}' OR the *string* between '{' and '}'. If no separator should be +// used (i.e. the separate values should be distinct arguments), then "{}" +// should be used as the separator. +// +// Options are extracted either from the current option by looking for +// the option name followed by an '=' or ':', or is taken from the +// following option IFF: +// - The current option does not contain a '=' or a ':' +// - The current option requires a value (i.e. not a Option type of ':') +// +// The `name' used in the option format string does NOT include any leading +// option indicator, such as '-', '--', or '/'. All three of these are +// permitted/required on any named option. +// +// Option bundling is permitted so long as: +// - '-' is used to start the option group +// - all of the bundled options are a single character +// - at most one of the bundled options accepts a value, and the value +// provided starts from the next character to the end of the string. +// +// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' +// as '-Dname=value'. +// +// Option processing is disabled by specifying "--". All options after "--" +// are returned by OptionSet.Parse() unchanged and unprocessed. +// +// Unprocessed options are returned from OptionSet.Parse(). +// +// Examples: +// int verbose = 0; +// OptionSet p = new OptionSet () +// .Add ("v", v => ++verbose) +// .Add ("name=|value=", v => Console.WriteLine (v)); +// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); +// +// The above would parse the argument string array, and would invoke the +// lambda expression three times, setting `verbose' to 3 when complete. +// It would also print out "A" and "B" to standard output. +// The returned array would contain the string "extra". +// +// C# 3.0 collection initializers are supported and encouraged: +// var p = new OptionSet () { +// { "h|?|help", v => ShowHelp () }, +// }; +// +// System.ComponentModel.TypeConverter is also supported, allowing the use of +// custom data types in the callback type; TypeConverter.ConvertFromString() +// is used to convert the value option to an instance of the specified +// type: +// +// var p = new OptionSet () { +// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, +// }; +// +// Random other tidbits: +// - Boolean options (those w/o '=' or ':' in the option format string) +// are explicitly enabled if they are followed with '+', and explicitly +// disabled if they are followed with '-': +// string a = null; +// var p = new OptionSet () { +// { "a", s => a = s }, +// }; +// p.Parse (new string[]{"-a"}); // sets v != null +// p.Parse (new string[]{"-a+"}); // sets v != null +// p.Parse (new string[]{"-a-"}); // sets v == null +// + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.IO; +using System.Runtime.Serialization; +using System.Security.Permissions; +using System.Text; +using System.Text.RegularExpressions; + +#if LINQ +using System.Linq; +#endif + +#if TEST +using NDesk.Options; +#endif + +#if NDESK_OPTIONS +namespace NDesk.Options +#else +namespace Mono.Options +#endif +{ + public class OptionValueCollection : IList, IList { + + List values = new List (); + OptionContext c; + + internal OptionValueCollection (OptionContext c) + { + this.c = c; + } + + #region ICollection + void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} + bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} + object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} + #endregion + + #region ICollection + public void Add (string item) {values.Add (item);} + public void Clear () {values.Clear ();} + public bool Contains (string item) {return values.Contains (item);} + public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} + public bool Remove (string item) {return values.Remove (item);} + public int Count {get {return values.Count;}} + public bool IsReadOnly {get {return false;}} + #endregion + + #region IEnumerable + IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} + #endregion + + #region IEnumerable + public IEnumerator GetEnumerator () {return values.GetEnumerator ();} + #endregion + + #region IList + int IList.Add (object value) {return (values as IList).Add (value);} + bool IList.Contains (object value) {return (values as IList).Contains (value);} + int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} + void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} + void IList.Remove (object value) {(values as IList).Remove (value);} + void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} + bool IList.IsFixedSize {get {return false;}} + object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} + #endregion + + #region IList + public int IndexOf (string item) {return values.IndexOf (item);} + public void Insert (int index, string item) {values.Insert (index, item);} + public void RemoveAt (int index) {values.RemoveAt (index);} + + private void AssertValid (int index) + { + if (c.Option == null) + throw new InvalidOperationException ("OptionContext.Option is null."); + if (index >= c.Option.MaxValueCount) + throw new ArgumentOutOfRangeException ("index"); + if (c.Option.OptionValueType == OptionValueType.Required && + index >= values.Count) + throw new OptionException (string.Format ( + c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), + c.OptionName); + } + + public string this [int index] { + get { + AssertValid (index); + return index >= values.Count ? null : values [index]; + } + set { + values [index] = value; + } + } + #endregion + + public List ToList () + { + return new List (values); + } + + public string[] ToArray () + { + return values.ToArray (); + } + + public override string ToString () + { + return string.Join (", ", values.ToArray ()); + } + } + + public class OptionContext { + private Option option; + private string name; + private int index; + private OptionSet set; + private OptionValueCollection c; + + public OptionContext (OptionSet set) + { + this.set = set; + this.c = new OptionValueCollection (this); + } + + public Option Option { + get {return option;} + set {option = value;} + } + + public string OptionName { + get {return name;} + set {name = value;} + } + + public int OptionIndex { + get {return index;} + set {index = value;} + } + + public OptionSet OptionSet { + get {return set;} + } + + public OptionValueCollection OptionValues { + get {return c;} + } + } + + public enum OptionValueType { + None, + Optional, + Required, + } + + public abstract class Option { + string prototype, description; + string[] names; + OptionValueType type; + int count; + string[] separators; + + protected Option (string prototype, string description) + : this (prototype, description, 1) + { + } + + protected Option (string prototype, string description, int maxValueCount) + { + if (prototype == null) + throw new ArgumentNullException ("prototype"); + if (prototype.Length == 0) + throw new ArgumentException ("Cannot be the empty string.", "prototype"); + if (maxValueCount < 0) + throw new ArgumentOutOfRangeException ("maxValueCount"); + + this.prototype = prototype; + this.names = prototype.Split ('|'); + this.description = description; + this.count = maxValueCount; + this.type = ParsePrototype (); + + if (this.count == 0 && type != OptionValueType.None) + throw new ArgumentException ( + "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + + "OptionValueType.Optional.", + "maxValueCount"); + if (this.type == OptionValueType.None && maxValueCount > 1) + throw new ArgumentException ( + string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), + "maxValueCount"); + if (Array.IndexOf (names, "<>") >= 0 && + ((names.Length == 1 && this.type != OptionValueType.None) || + (names.Length > 1 && this.MaxValueCount > 1))) + throw new ArgumentException ( + "The default option handler '<>' cannot require values.", + "prototype"); + } + + public string Prototype {get {return prototype;}} + public string Description {get {return description;}} + public OptionValueType OptionValueType {get {return type;}} + public int MaxValueCount {get {return count;}} + + public string[] GetNames () + { + return (string[]) names.Clone (); + } + + public string[] GetValueSeparators () + { + if (separators == null) + return new string [0]; + return (string[]) separators.Clone (); + } + + protected static T Parse (string value, OptionContext c) + { + Type tt = typeof (T); + bool nullable = tt.IsValueType && tt.IsGenericType && + !tt.IsGenericTypeDefinition && + tt.GetGenericTypeDefinition () == typeof (Nullable<>); + Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T); + TypeConverter conv = TypeDescriptor.GetConverter (targetType); + T t = default (T); + try { + if (value != null) + t = (T) conv.ConvertFromString (value); + } + catch (Exception e) { + throw new OptionException ( + string.Format ( + c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), + value, targetType.Name, c.OptionName), + c.OptionName, e); + } + return t; + } + + internal string[] Names {get {return names;}} + internal string[] ValueSeparators {get {return separators;}} + + static readonly char[] NameTerminator = new char[]{'=', ':'}; + + private OptionValueType ParsePrototype () + { + char type = '\0'; + List seps = new List (); + for (int i = 0; i < names.Length; ++i) { + string name = names [i]; + if (name.Length == 0) + throw new ArgumentException ("Empty option names are not supported.", "prototype"); + + int end = name.IndexOfAny (NameTerminator); + if (end == -1) + continue; + names [i] = name.Substring (0, end); + if (type == '\0' || type == name [end]) + type = name [end]; + else + throw new ArgumentException ( + string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), + "prototype"); + AddSeparators (name, end, seps); + } + + if (type == '\0') + return OptionValueType.None; + + if (count <= 1 && seps.Count != 0) + throw new ArgumentException ( + string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), + "prototype"); + if (count > 1) { + if (seps.Count == 0) + this.separators = new string[]{":", "="}; + else if (seps.Count == 1 && seps [0].Length == 0) + this.separators = null; + else + this.separators = seps.ToArray (); + } + + return type == '=' ? OptionValueType.Required : OptionValueType.Optional; + } + + private static void AddSeparators (string name, int end, ICollection seps) + { + int start = -1; + for (int i = end+1; i < name.Length; ++i) { + switch (name [i]) { + case '{': + if (start != -1) + throw new ArgumentException ( + string.Format ("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + start = i+1; + break; + case '}': + if (start == -1) + throw new ArgumentException ( + string.Format ("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + seps.Add (name.Substring (start, i-start)); + start = -1; + break; + default: + if (start == -1) + seps.Add (name [i].ToString ()); + break; + } + } + if (start != -1) + throw new ArgumentException ( + string.Format ("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + } + + public void Invoke (OptionContext c) + { + OnParseComplete (c); + c.OptionName = null; + c.Option = null; + c.OptionValues.Clear (); + } + + protected abstract void OnParseComplete (OptionContext c); + + public override string ToString () + { + return Prototype; + } + } + + [Serializable] + public class OptionException : Exception { + private string option; + + public OptionException () + { + } + + public OptionException (string message, string optionName) + : base (message) + { + this.option = optionName; + } + + public OptionException (string message, string optionName, Exception innerException) + : base (message, innerException) + { + this.option = optionName; + } + + protected OptionException (SerializationInfo info, StreamingContext context) + : base (info, context) + { + this.option = info.GetString ("OptionName"); + } + + public string OptionName { + get {return this.option;} + } + + [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] + public override void GetObjectData (SerializationInfo info, StreamingContext context) + { + base.GetObjectData (info, context); + info.AddValue ("OptionName", option); + } + } + + public delegate void OptionAction (TKey key, TValue value); + + public class OptionSet : KeyedCollection + { + public OptionSet () + : this (delegate (string f) {return f;}) + { + } + + public OptionSet (Converter localizer) + { + this.localizer = localizer; + } + + Converter localizer; + + public Converter MessageLocalizer { + get {return localizer;} + } + + protected override string GetKeyForItem (Option item) + { + if (item == null) + throw new ArgumentNullException ("option"); + if (item.Names != null && item.Names.Length > 0) + return item.Names [0]; + // This should never happen, as it's invalid for Option to be + // constructed w/o any names. + throw new InvalidOperationException ("Option has no names!"); + } + + [Obsolete ("Use KeyedCollection.this[string]")] + protected Option GetOptionForName (string option) + { + if (option == null) + throw new ArgumentNullException ("option"); + try { + return base [option]; + } + catch (KeyNotFoundException) { + return null; + } + } + + protected override void InsertItem (int index, Option item) + { + base.InsertItem (index, item); + AddImpl (item); + } + + protected override void RemoveItem (int index) + { + base.RemoveItem (index); + Option p = Items [index]; + // KeyedCollection.RemoveItem() handles the 0th item + for (int i = 1; i < p.Names.Length; ++i) { + Dictionary.Remove (p.Names [i]); + } + } + + protected override void SetItem (int index, Option item) + { + base.SetItem (index, item); + RemoveItem (index); + AddImpl (item); + } + + private void AddImpl (Option option) + { + if (option == null) + throw new ArgumentNullException ("option"); + List added = new List (option.Names.Length); + try { + // KeyedCollection.InsertItem/SetItem handle the 0th name. + for (int i = 1; i < option.Names.Length; ++i) { + Dictionary.Add (option.Names [i], option); + added.Add (option.Names [i]); + } + } + catch (Exception) { + foreach (string name in added) + Dictionary.Remove (name); + throw; + } + } + + public new OptionSet Add (Option option) + { + base.Add (option); + return this; + } + + sealed class ActionOption : Option { + Action action; + + public ActionOption (string prototype, string description, int count, Action action) + : base (prototype, description, count) + { + if (action == null) + throw new ArgumentNullException ("action"); + this.action = action; + } + + protected override void OnParseComplete (OptionContext c) + { + action (c.OptionValues); + } + } + + public OptionSet Add (string prototype, Action action) + { + return Add (prototype, null, action); + } + + public OptionSet Add (string prototype, string description, Action action) + { + if (action == null) + throw new ArgumentNullException ("action"); + Option p = new ActionOption (prototype, description, 1, + delegate (OptionValueCollection v) { action (v [0]); }); + base.Add (p); + return this; + } + + public OptionSet Add (string prototype, OptionAction action) + { + return Add (prototype, null, action); + } + + public OptionSet Add (string prototype, string description, OptionAction action) + { + if (action == null) + throw new ArgumentNullException ("action"); + Option p = new ActionOption (prototype, description, 2, + delegate (OptionValueCollection v) {action (v [0], v [1]);}); + base.Add (p); + return this; + } + + sealed class ActionOption : Option { + Action action; + + public ActionOption (string prototype, string description, Action action) + : base (prototype, description, 1) + { + if (action == null) + throw new ArgumentNullException ("action"); + this.action = action; + } + + protected override void OnParseComplete (OptionContext c) + { + action (Parse (c.OptionValues [0], c)); + } + } + + sealed class ActionOption : Option { + OptionAction action; + + public ActionOption (string prototype, string description, OptionAction action) + : base (prototype, description, 2) + { + if (action == null) + throw new ArgumentNullException ("action"); + this.action = action; + } + + protected override void OnParseComplete (OptionContext c) + { + action ( + Parse (c.OptionValues [0], c), + Parse (c.OptionValues [1], c)); + } + } + + public OptionSet Add (string prototype, Action action) + { + return Add (prototype, null, action); + } + + public OptionSet Add (string prototype, string description, Action action) + { + return Add (new ActionOption (prototype, description, action)); + } + + public OptionSet Add (string prototype, OptionAction action) + { + return Add (prototype, null, action); + } + + public OptionSet Add (string prototype, string description, OptionAction action) + { + return Add (new ActionOption (prototype, description, action)); + } + + protected virtual OptionContext CreateOptionContext () + { + return new OptionContext (this); + } + +#if LINQ + public List Parse (IEnumerable arguments) + { + bool process = true; + OptionContext c = CreateOptionContext (); + c.OptionIndex = -1; + var def = GetOptionForName ("<>"); + var unprocessed = + from argument in arguments + where ++c.OptionIndex >= 0 && (process || def != null) + ? process + ? argument == "--" + ? (process = false) + : !Parse (argument, c) + ? def != null + ? Unprocessed (null, def, c, argument) + : true + : false + : def != null + ? Unprocessed (null, def, c, argument) + : true + : true + select argument; + List r = unprocessed.ToList (); + if (c.Option != null) + c.Option.Invoke (c); + return r; + } +#else + public List Parse (IEnumerable arguments) + { + OptionContext c = CreateOptionContext (); + c.OptionIndex = -1; + bool process = true; + List unprocessed = new List (); + Option def = Contains ("<>") ? this ["<>"] : null; + foreach (string argument in arguments) { + ++c.OptionIndex; + if (argument == "--") { + process = false; + continue; + } + if (!process) { + Unprocessed (unprocessed, def, c, argument); + continue; + } + if (!Parse (argument, c)) + Unprocessed (unprocessed, def, c, argument); + } + if (c.Option != null) + c.Option.Invoke (c); + return unprocessed; + } +#endif + + private static bool Unprocessed (ICollection extra, Option def, OptionContext c, string argument) + { + if (def == null) { + extra.Add (argument); + return false; + } + c.OptionValues.Add (argument); + c.Option = def; + c.Option.Invoke (c); + return false; + } + + private readonly Regex ValueOption = new Regex ( + @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$"); + + protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) + { + if (argument == null) + throw new ArgumentNullException ("argument"); + + flag = name = sep = value = null; + Match m = ValueOption.Match (argument); + if (!m.Success) { + return false; + } + flag = m.Groups ["flag"].Value; + name = m.Groups ["name"].Value; + if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { + sep = m.Groups ["sep"].Value; + value = m.Groups ["value"].Value; + } + return true; + } + + protected virtual bool Parse (string argument, OptionContext c) + { + if (c.Option != null) { + ParseValue (argument, c); + return true; + } + + string f, n, s, v; + if (!GetOptionParts (argument, out f, out n, out s, out v)) + return false; + + Option p; + if (Contains (n)) { + p = this [n]; + c.OptionName = f + n; + c.Option = p; + switch (p.OptionValueType) { + case OptionValueType.None: + c.OptionValues.Add (n); + c.Option.Invoke (c); + break; + case OptionValueType.Optional: + case OptionValueType.Required: + ParseValue (v, c); + break; + } + return true; + } + // no match; is it a bool option? + if (ParseBool (argument, n, c)) + return true; + // is it a bundled option? + if (ParseBundledValue (f, string.Concat (n + s + v), c)) + return true; + + return false; + } + + private void ParseValue (string option, OptionContext c) + { + if (option != null) + foreach (string o in c.Option.ValueSeparators != null + ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) + : new string[]{option}) { + c.OptionValues.Add (o); + } + if (c.OptionValues.Count == c.Option.MaxValueCount || + c.Option.OptionValueType == OptionValueType.Optional) + c.Option.Invoke (c); + else if (c.OptionValues.Count > c.Option.MaxValueCount) { + throw new OptionException (localizer (string.Format ( + "Error: Found {0} option values when expecting {1}.", + c.OptionValues.Count, c.Option.MaxValueCount)), + c.OptionName); + } + } + + private bool ParseBool (string option, string n, OptionContext c) + { + Option p; + string rn; + if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && + Contains ((rn = n.Substring (0, n.Length-1)))) { + p = this [rn]; + string v = n [n.Length-1] == '+' ? option : null; + c.OptionName = option; + c.Option = p; + c.OptionValues.Add (v); + p.Invoke (c); + return true; + } + return false; + } + + private bool ParseBundledValue (string f, string n, OptionContext c) + { + if (f != "-") + return false; + for (int i = 0; i < n.Length; ++i) { + Option p; + string opt = f + n [i].ToString (); + string rn = n [i].ToString (); + if (!Contains (rn)) { + if (i == 0) + return false; + throw new OptionException (string.Format (localizer ( + "Cannot bundle unregistered option '{0}'."), opt), opt); + } + p = this [rn]; + switch (p.OptionValueType) { + case OptionValueType.None: + Invoke (c, opt, n, p); + break; + case OptionValueType.Optional: + case OptionValueType.Required: { + string v = n.Substring (i+1); + c.Option = p; + c.OptionName = opt; + ParseValue (v.Length != 0 ? v : null, c); + return true; + } + default: + throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); + } + } + return true; + } + + private static void Invoke (OptionContext c, string name, string value, Option option) + { + c.OptionName = name; + c.Option = option; + c.OptionValues.Add (value); + option.Invoke (c); + } + + private const int OptionWidth = 29; + + public void WriteOptionDescriptions (TextWriter o) + { + foreach (Option p in this) { + int written = 0; + if (!WriteOptionPrototype (o, p, ref written)) + continue; + + if (written < OptionWidth) + o.Write (new string (' ', OptionWidth - written)); + else { + o.WriteLine (); + o.Write (new string (' ', OptionWidth)); + } + + List lines = GetLines (localizer (GetDescription (p.Description))); + o.WriteLine (lines [0]); + string prefix = new string (' ', OptionWidth+2); + for (int i = 1; i < lines.Count; ++i) { + o.Write (prefix); + o.WriteLine (lines [i]); + } + } + } + + bool WriteOptionPrototype (TextWriter o, Option p, ref int written) + { + string[] names = p.Names; + + int i = GetNextOptionIndex (names, 0); + if (i == names.Length) + return false; + + if (names [i].Length == 1) { + Write (o, ref written, " -"); + Write (o, ref written, names [0]); + } + else { + Write (o, ref written, " --"); + Write (o, ref written, names [0]); + } + + for ( i = GetNextOptionIndex (names, i+1); + i < names.Length; i = GetNextOptionIndex (names, i+1)) { + Write (o, ref written, ", "); + Write (o, ref written, names [i].Length == 1 ? "-" : "--"); + Write (o, ref written, names [i]); + } + + if (p.OptionValueType == OptionValueType.Optional || + p.OptionValueType == OptionValueType.Required) { + if (p.OptionValueType == OptionValueType.Optional) { + Write (o, ref written, localizer ("[")); + } + Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); + string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 + ? p.ValueSeparators [0] + : " "; + for (int c = 1; c < p.MaxValueCount; ++c) { + Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); + } + if (p.OptionValueType == OptionValueType.Optional) { + Write (o, ref written, localizer ("]")); + } + } + return true; + } + + static int GetNextOptionIndex (string[] names, int i) + { + while (i < names.Length && names [i] == "<>") { + ++i; + } + return i; + } + + static void Write (TextWriter o, ref int n, string s) + { + n += s.Length; + o.Write (s); + } + + private static string GetArgumentName (int index, int maxIndex, string description) + { + if (description == null) + return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); + string[] nameStart; + if (maxIndex == 1) + nameStart = new string[]{"{0:", "{"}; + else + nameStart = new string[]{"{" + index + ":"}; + for (int i = 0; i < nameStart.Length; ++i) { + int start, j = 0; + do { + start = description.IndexOf (nameStart [i], j); + } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); + if (start == -1) + continue; + int end = description.IndexOf ("}", start); + if (end == -1) + continue; + return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); + } + return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); + } + + private static string GetDescription (string description) + { + if (description == null) + return string.Empty; + StringBuilder sb = new StringBuilder (description.Length); + int start = -1; + for (int i = 0; i < description.Length; ++i) { + switch (description [i]) { + case '{': + if (i == start) { + sb.Append ('{'); + start = -1; + } + else if (start < 0) + start = i + 1; + break; + case '}': + if (start < 0) { + if ((i+1) == description.Length || description [i+1] != '}') + throw new InvalidOperationException ("Invalid option description: " + description); + ++i; + sb.Append ("}"); + } + else { + sb.Append (description.Substring (start, i - start)); + start = -1; + } + break; + case ':': + if (start < 0) + goto default; + start = i + 1; + break; + default: + if (start < 0) + sb.Append (description [i]); + break; + } + } + return sb.ToString (); + } + + private static List GetLines (string description) + { + List lines = new List (); + if (string.IsNullOrEmpty (description)) { + lines.Add (string.Empty); + return lines; + } + int length = 80 - OptionWidth - 2; + int start = 0, end; + do { + end = GetLineEnd (start, length, description); + bool cont = false; + if (end < description.Length) { + char c = description [end]; + if (c == '-' || (char.IsWhiteSpace (c) && c != '\n')) + ++end; + else if (c != '\n') { + cont = true; + --end; + } + } + lines.Add (description.Substring (start, end - start)); + if (cont) { + lines [lines.Count-1] += "-"; + } + start = end; + if (start < description.Length && description [start] == '\n') + ++start; + } while (end < description.Length); + return lines; + } + + private static int GetLineEnd (int start, int length, string description) + { + int end = System.Math.Min (start + length, description.Length); + int sep = -1; + for (int i = start; i < end; ++i) { + switch (description [i]) { + case ' ': + case '\t': + case '\v': + case '-': + case ',': + case '.': + case ';': + sep = i; + break; + case '\n': + return i; + } + } + if (sep == -1 || end == description.Length) + return end; + return sep; + } + } +} + diff --git a/SparkleShare/Windows/tools/TextTemplating/TextTransform/TextTransform.cs b/SparkleShare/Windows/tools/TextTemplating/TextTransform/TextTransform.cs new file mode 100644 index 00000000..1f66bff1 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/TextTransform/TextTransform.cs @@ -0,0 +1,174 @@ +// +// Main.cs +// +// Author: +// Michael Hutchinson +// +// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using System.IO; +using System.Collections.Generic; +using Mono.Options; + +namespace Mono.TextTemplating +{ + class TextTransform + { + static OptionSet optionSet; + const string name ="TextTransform.exe"; + + public static int Main (string[] args) + { + if (args.Length == 0) { + ShowHelp (true); + } + + var generator = new TemplateGenerator (); + string outputFile = null, inputFile = null; + var directives = new List (); + var parameters = new List (); + var session = new Microsoft.VisualStudio.TextTemplating.TextTemplatingSession (); + string preprocess = null; + + optionSet = new OptionSet () { + { "o=|out=", "The name of the output {file}", s => outputFile = s }, + { "r=", "Assemblies to reference", s => generator.Refs.Add (s) }, + { "u=", "Namespaces to import <{0:namespace}>", s => generator.Imports.Add (s) }, + { "I=", "Paths to search for included files", s => generator.IncludePaths.Add (s) }, + { "P=", "Paths to search for referenced assemblies", s => generator.ReferencePaths.Add (s) }, + { "dp=", "Directive processor (name!class!assembly)", s => directives.Add (s) }, + { "a=", "Parameters ([processorName]![directiveName]!name!value)", s => parameters.Add (s) }, + { "h|?|help", "Show help", s => ShowHelp (false) }, + // { "k=,", "Session {key},{value} pairs", (s, t) => session.Add (s, t) }, + { "c=", "Preprocess the template into {0:class}", (s) => preprocess = s }, + }; + + var remainingArgs = optionSet.Parse (args); + + if (string.IsNullOrEmpty (outputFile)) { + Console.Error.WriteLine ("No output file specified."); + return -1; + } + + if (remainingArgs.Count != 1) { + Console.Error.WriteLine ("No input file specified."); + return -1; + } + inputFile = remainingArgs [0]; + + if (!File.Exists (inputFile)) { + Console.Error.WriteLine ("Input file '{0}' does not exist."); + return -1; + } + + //FIXME: implement quoting and escaping for values + foreach (var par in parameters) { + var split = par.Split ('!'); + if (split.Length < 2) { + Console.Error.WriteLine ("Parameter does not have enough values: {0}", par); + return -1; + } + if (split.Length > 2) { + Console.Error.WriteLine ("Parameter has too many values: {0}", par); + return -1; + } + string name = split[split.Length-2]; + string val = split[split.Length-1]; + if (string.IsNullOrEmpty (name)) { + Console.Error.WriteLine ("Parameter has no name: {0}", par); + return -1; + } + generator.AddParameter (split.Length > 3? split[0] : null, split.Length > 2? split[split.Length-3] : null, name, val); + } + + foreach (var dir in directives) { + var split = dir.Split ('!'); + if (split.Length != 3) { + Console.Error.WriteLine ("Directive does not have correct number of values: {0}", dir); + return -1; + } + foreach (var s in split) { + if (string.IsNullOrEmpty (s)) { + Console.Error.WriteLine ("Directive has missing value: {0}", dir); + return -1; + } + } + generator.AddDirectiveProcessor (split[0], split[1], split[2]); + } + + if (preprocess == null) { + Console.Write ("Processing '{0}'... ", inputFile); + generator.ProcessTemplate (inputFile, outputFile); + if (generator.Errors.HasErrors) { + Console.WriteLine ("failed."); + } else { + Console.WriteLine ("completed successfully."); + } + } else { + string className = preprocess; + string classNamespace = null; + int s = preprocess.LastIndexOf ('.'); + if (s > 0) { + classNamespace = preprocess.Substring (0, s); + className = preprocess.Substring (s + 1); + } + + Console.Write ("Preprocessing '{0}' into class '{1}.{2}'... ", inputFile, classNamespace, className); + string language; + string[] references; + generator.PreprocessTemplate (inputFile, className, classNamespace, outputFile, System.Text.Encoding.UTF8, + out language, out references); + if (generator.Errors.HasErrors) { + Console.WriteLine ("failed."); + } else { + Console.WriteLine ("completed successfully:"); + Console.WriteLine (" Language: {0}", language); + if (references != null && references.Length > 0) { + Console.WriteLine (" References:"); + foreach (string r in references) + Console.WriteLine (" {0}", r); + } + } + } + + foreach (System.CodeDom.Compiler.CompilerError err in generator.Errors) + Console.Error.WriteLine ("{0}({1},{2}): {3} {4}", err.FileName, err.Line, err.Column, + err.IsWarning? "WARNING" : "ERROR", err.ErrorText); + + return generator.Errors.HasErrors? -1 : 0; + } + + static void ShowHelp (bool concise) + { + Console.WriteLine ("TextTransform command line T4 processor"); + Console.WriteLine ("Usage: {0} [options] input-file", name); + if (concise) { + Console.WriteLine ("Use --help to display options."); + } else { + Console.WriteLine ("Options:"); + optionSet.WriteOptionDescriptions (System.Console.Out); + } + Console.WriteLine (); + Environment.Exit (0); + } + } +} \ No newline at end of file diff --git a/SparkleShare/Windows/tools/TextTemplating/TextTransform/TextTransform.csproj b/SparkleShare/Windows/tools/TextTemplating/TextTransform/TextTransform.csproj new file mode 100644 index 00000000..5820f5ac --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/TextTransform/TextTransform.csproj @@ -0,0 +1,62 @@ + + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {D1D35409-C814-47F6-B038-B9B5BF0FE490} + Exe + TextTransform + Mono.TextTemplating + + + true + full + false + ..\bin + DEBUG + prompt + 4 + -o:out.txt in.tt + + + none + false + ..\bin + prompt + 4 + + + + + + + + + + + + + {A2364D6A-00EF-417C-80A6-815726C70032} + Mono.TextTemplating + False + + + + + + + + + + + + + + + + + + + diff --git a/SparkleShare/Windows/tools/TextTemplating/build.cmd b/SparkleShare/Windows/tools/TextTemplating/build.cmd new file mode 100644 index 00000000..8e0ecf30 --- /dev/null +++ b/SparkleShare/Windows/tools/TextTemplating/build.cmd @@ -0,0 +1,5 @@ +@echo off +set WinDirNet=%WinDir%\Microsoft.NET\Framework +set msbuild="%WinDirNet%\v4.0.30319\msbuild.exe" + +%msbuild% /t:Rebuild /p:Configuration=Release /p:Platform="Any CPU" %~dp0\TextTemplating.sln diff --git a/SparkleShare/Windows/tools/addmedia.xlst b/SparkleShare/Windows/tools/addmedia.xlst new file mode 100644 index 00000000..66b70765 --- /dev/null +++ b/SparkleShare/Windows/tools/addmedia.xlst @@ -0,0 +1,23 @@ + + + + + + + + + + + + + 2 + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Tests/Gettext.Cs.Tests.csproj b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Tests/Gettext.Cs.Tests.csproj new file mode 100644 index 00000000..1bc30c81 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Tests/Gettext.Cs.Tests.csproj @@ -0,0 +1,67 @@ + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {C4B4300B-5B96-4F43-BD7D-517A29693B30} + Library + Properties + Gettext.Cs.Tests + Gettext.Cs.Tests + v3.5 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + 3.5 + + + + 3.5 + + + + 3.5 + + + + + + + + + {D8869765-AB47-4C03-B2C5-E5498A55CA79} + Gettext.Cs + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Tests/PoParserTest.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Tests/PoParserTest.cs new file mode 100644 index 00000000..57c8e936 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Tests/PoParserTest.cs @@ -0,0 +1,64 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + +using Gettext.Cs; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.IO; +using System.Collections.Generic; +using System; +using System.Linq; + +namespace Gettext.Cs.Tests +{ + /// + ///This is a test class for PoParserTest and is intended + ///to contain all PoParserTest Unit Tests + /// + [TestClass()] + public class PoParserTest + { + /// + /// Tests slashes in parsed strings + /// + /// + [TestMethod()] + public void ParseIntoDictionaryStringWithSlashesTest() + { + string msgid = @"The type of parameter \""${0}\"" is not supported"; + string msgstr = @"Il tipo del parametro \""${0}\"" non è supportato"; + + string parsedMsgid = @"The type of parameter ""${0}"" is not supported"; + string parsedMsgstr = @"Il tipo del parametro ""${0}"" non è supportato"; + + PoParser target = new PoParser(); + TextReader reader = new StringReader(String.Format(@" + msgid ""{0}"" + msgstr ""{1}"" + ", msgid, msgstr)); + + var actual = target.ParseIntoDictionary(reader); + + Assert.AreEqual(1, actual.Count, "Parsed dictionary entries count do not match"); + Assert.AreEqual(parsedMsgid, actual.Keys.ToArray()[0], "Key does not match"); + Assert.AreEqual(parsedMsgstr, actual.Values.ToArray()[0], "Value does not match"); + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Tests/Properties/AssemblyInfo.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..ef49090d --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,57 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Gettext.Cs.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Gettext.Cs.Tests")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM componenets. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("532f2d56-549a-474c-b46b-82fc90f1db64")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Web/Controls/AspTranslate.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Web/Controls/AspTranslate.cs new file mode 100644 index 00000000..263e6e8d --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Web/Controls/AspTranslate.cs @@ -0,0 +1,48 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System.Web.UI; + + +namespace Gettext.Cs.Web +{ + [ParseChildren(false)] + public abstract class AspTranslate : Control + { + string content; + + protected override void AddParsedSubObject(object obj) + { + if (obj is LiteralControl) + { + content = Translate(((LiteralControl)obj).Text); + } + } + + protected override void Render(HtmlTextWriter writer) + { + writer.Write(content); + } + + protected abstract string Translate(string text); + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Web/Gettext.Cs.Web.csproj b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Web/Gettext.Cs.Web.csproj new file mode 100644 index 00000000..ac6930a9 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Web/Gettext.Cs.Web.csproj @@ -0,0 +1,60 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {38474466-DA21-4D19-A4D8-E2E7918480D6} + Library + Properties + Gettext.Cs.Web + Gettext.Cs.Web + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + 3.5 + + + + 3.5 + + + 3.5 + + + + + + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Web/Properties/AssemblyInfo.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Web/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..510861c0 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs.Web/Properties/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Gettext.Cs.Web")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Gettext.Cs.Web")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("efc9a6d8-33cd-4cc5-8984-90847fea390e")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Gettext.Cs.csproj b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Gettext.Cs.csproj new file mode 100644 index 00000000..2127e2c4 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Gettext.Cs.csproj @@ -0,0 +1,83 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {D8869765-AB47-4C03-B2C5-E5498A55CA79} + Library + Properties + Gettext.Cs + Gettext.Cs + v3.5 + 512 + + + true + full + false + ..\..\..\..\..\..\..\bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + ..\..\..\..\..\..\..\bin\ + TRACE + prompt + 4 + + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + + + + + + + True + True + Strings.tt + + + + + TextTemplatingFileGenerator + Strings.cs + PreserveNewest + + + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Parser/ParserRequestor.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Parser/ParserRequestor.cs new file mode 100644 index 00000000..d2888cfa --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Parser/ParserRequestor.cs @@ -0,0 +1,55 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Gettext.Cs +{ + /// + /// Interface for retrieving data from the parser. + /// + public interface IGettextParserRequestor + { + /// + /// Handles a key value pair parsed from the po file. + /// + void Handle(string key, string value); + } + + /// + /// Collects data from the parser into a dictionary. + /// + public class DictionaryGettextParserRequestor : Dictionary, IGettextParserRequestor + { + #region IGettextParserRequestor Members + + public void Handle(string key, string value) + { + this[key] = value; + } + + #endregion + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Parser/PoParser.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Parser/PoParser.cs new file mode 100644 index 00000000..b80d0bc9 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Parser/PoParser.cs @@ -0,0 +1,149 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; + +namespace Gettext.Cs +{ + /// + /// Parses standard po files. + /// + public class PoParser + { + /// + /// Parses an input po file. + /// + public void Parse(TextReader reader, IGettextParserRequestor requestor) + { + const int StateWaitingKey = 1; + const int StateConsumingKey = 2; + const int StateConsumingValue = 3; + + int state = StateWaitingKey; + + StringBuilder currentKey = null; + StringBuilder currentValue = null; + + string line; + while(true) { + line = reader.ReadLine(); + line = line == null ? null : line.Trim(); + if (line == null || line.Length == 0) + { + if (state == StateConsumingValue && + currentKey != null && + currentValue != null) + { + requestor.Handle(currentKey.ToString().Replace("\\n", "\n").Replace("\\\"", "\""), + currentValue.ToString().Replace("\\n", "\n").Replace("\\\"", "\"")); + currentKey = null; + currentValue = null; + } + + if (line == null) + break; + + state = StateWaitingKey; + continue; + } + else if (line[0] == '#') + { + continue; + } + + bool isMsgId = line.StartsWith("msgid "); + bool isMsgStr = !isMsgId && line.StartsWith("msgstr "); + + if (isMsgId || isMsgStr) + { + state = isMsgId ? StateConsumingKey : StateConsumingValue; + + int firstQuote = line.IndexOf('"'); + if (firstQuote == -1) + continue; + + int secondQuote = line.IndexOf('"', firstQuote + 1); + while (secondQuote != -1 && line[secondQuote - 1] == '\\') + secondQuote = line.IndexOf('"', secondQuote + 1); + if (secondQuote == -1) + continue; + + string piece = line.Substring(firstQuote + 1, secondQuote - firstQuote - 1); + + if (isMsgId) + { + currentKey = new StringBuilder(); + currentKey.Append(piece); + } + else + { + currentValue = new StringBuilder(); + currentValue.Append(piece); + } + } + else if (line[0] == '"') + { + if (line[line.Length - 1] == '"') + { + line = line.Substring(1, line.Length - 2); + } + else + { + line = line.Substring(1, line.Length - 1); + } + + switch (state) + { + case StateConsumingKey: + currentKey.Append(line); + break; + case StateConsumingValue: + currentValue.Append(line); + break; + } + } + } + } + + /// + /// Parses an input po file. + /// + public void Parse(string text, IGettextParserRequestor requestor) + { + Parse(new StringReader(text), requestor); + } + + /// + /// Parses an input po file into a dictionary. + /// + public Dictionary ParseIntoDictionary(TextReader reader) + { + var requestor = new DictionaryGettextParserRequestor(); + Parse(reader, requestor); + return requestor; + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Properties/AssemblyInfo.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..51d908d2 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Properties/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Gettext.Cs")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Gettext.Cs")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1c3b8e32-0c8d-4d0f-ae9b-d38e4b45690a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/DatabaseResourceManager.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/DatabaseResourceManager.cs new file mode 100644 index 00000000..12b224c7 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/DatabaseResourceManager.cs @@ -0,0 +1,86 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Collections; +using System.Globalization; +using System.Resources; +using System.Configuration; + +namespace Gettext.Cs +{ + public class DatabaseResourceManager : System.Resources.ResourceManager + { + private string dsn; + private string sp; + + public DatabaseResourceManager() + : base() + { + this.dsn = ConfigurationManager.AppSettings["Gettext.ConnectionString"] ?? ConfigurationManager.ConnectionStrings["Gettext"].ConnectionString; + ResourceSets = new System.Collections.Hashtable(); + } + + public DatabaseResourceManager(string storedProcedure) + : this() + { + this.sp = storedProcedure; + } + + // Hack: kept for compatibility + public DatabaseResourceManager(string name, string path, string fileformat) + : this() + { + } + + protected override ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) + { + DatabaseResourceSet rs = null; + + if (ResourceSets.Contains(culture.Name)) + { + rs = ResourceSets[culture.Name] as DatabaseResourceSet; + } + else + { + lock (ResourceSets) + { + // Check hash table once again after lock is set + if (ResourceSets.Contains(culture.Name)) + { + rs = ResourceSets[culture.Name] as DatabaseResourceSet; + } + else + { + rs = new DatabaseResourceSet(dsn, culture, sp); + ResourceSets.Add(culture.Name, rs); + } + } + } + + return rs; + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/DatabaseResourceReader.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/DatabaseResourceReader.cs new file mode 100644 index 00000000..eab8fcc7 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/DatabaseResourceReader.cs @@ -0,0 +1,121 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Resources; +using System.Collections; +using System.Data.SqlClient; +using System.Globalization; +using System.Configuration; + +namespace Gettext.Cs +{ + public class DatabaseResourceReader : IResourceReader + { + private string dsn; + private string language; + private string sp; + + public DatabaseResourceReader(string dsn, CultureInfo culture) + { + this.dsn = dsn; + this.language = culture.Name; + } + + public DatabaseResourceReader(string dsn, CultureInfo culture, string sp) + { + this.sp = sp; + this.dsn = dsn; + this.language = culture.Name; + } + + public System.Collections.IDictionaryEnumerator GetEnumerator() + { + Hashtable dict = new Hashtable(); + + SqlConnection connection = new SqlConnection(dsn); + SqlCommand command = connection.CreateCommand(); + + if (language == "") + language = CultureInfo.InvariantCulture.Name; + + // Use stored procedure or plain text + if (sp == null) + { + command.CommandText = string.Format("SELECT MessageKey, MessageValue FROM Message WHERE Culture = '{0}'", language); + } + else + { + command.CommandText = sp; + command.CommandType = System.Data.CommandType.StoredProcedure; + command.Parameters.AddWithValue("@culture", language); + } + + try + { + connection.Open(); + + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + if (reader.GetValue(1) != System.DBNull.Value) + { + dict[reader.GetString(0)] = reader.GetString(1); + } + } + } + + } + catch + { + bool raise = false; + if (bool.TryParse(ConfigurationManager.AppSettings["Gettext.Throw"], out raise) && raise) + { + throw; + } + } + finally + { + connection.Close(); + } + + return dict.GetEnumerator(); + } + + public void Close() + { + } + + IEnumerator IEnumerable.GetEnumerator() + { + return this.GetEnumerator(); + } + + void IDisposable.Dispose() + { + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/DatabaseResourceSet.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/DatabaseResourceSet.cs new file mode 100644 index 00000000..c55b50a2 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/DatabaseResourceSet.cs @@ -0,0 +1,50 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Resources; +using System.Globalization; + +namespace Gettext.Cs +{ + public class DatabaseResourceSet : ResourceSet + { + internal DatabaseResourceSet(string dsn, CultureInfo culture) + : base (new DatabaseResourceReader(dsn, culture)) + { + } + + internal DatabaseResourceSet(string dsn, CultureInfo culture, string sp) + : base(new DatabaseResourceReader(dsn, culture, sp)) + { + } + + public override Type GetDefaultReader() + { + return typeof(DatabaseResourceReader); + } + } + +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/FileBasedResourceManager.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/FileBasedResourceManager.cs new file mode 100644 index 00000000..ec6c38b9 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/FileBasedResourceManager.cs @@ -0,0 +1,295 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; +using System.Reflection; +using System.IO; +using System.Collections; + +namespace Gettext.Cs +{ + /// + /// Extendable file based resource manager. + /// + public class FileBasedResourceManager : System.Resources.ResourceManager + { + #region Properties + + string path; + string fileformat; + + /// + /// Path to retrieve the files from. + /// + public string Path + { + get { return path; } + set { path = value; } + } + + /// + /// Format of the resource set po file based on {{culture}} and {{resource}} placeholders. + /// + public string FileFormat + { + get { return fileformat; } + set { fileformat = value; } + } + + #endregion + + #region Notification Events + + /// + /// Arguments for events related to the creation, successful or not, of a resource set. + /// + public class ResourceSetCreationEventArgs : EventArgs + { + /// + /// Exception in case of error, null on success. + /// + public Exception Exception { get; set; } + + /// + /// FileName from where the resource set was loaded. + /// + public String FileName { get; set; } + + /// + /// Type of the resource set being initialized. + /// + public Type ResourceSetType { get; set; } + + /// + /// Instance of the resource set created, may be null on error. + /// + public System.Resources.ResourceSet ResourceSet { get; set; } + + /// + /// Whether the creation was successful. + /// + public bool Success { get; set; } + } + + /// + /// Event that notifies the successful creation of a resource set. + /// + public event EventHandler CreatedResourceSet; + + /// + /// Event that notifies an error creating a resource set. + /// + public event EventHandler FailedResourceSet; + + protected void RaiseCreatedResourceSet(string filename, System.Resources.ResourceSet set) + { + var handler = CreatedResourceSet; + if (handler != null) + { + handler(this, new ResourceSetCreationEventArgs + { + FileName = filename, + ResourceSet = set, + ResourceSetType = this.ResourceSetType, + Success = true + }); + } + } + + protected void RaiseFailedResourceSet(string filename, Exception ex) + { + var handler = FailedResourceSet; + if (handler != null) + { + handler(this, new ResourceSetCreationEventArgs + { + FileName = filename, + ResourceSet = null, + ResourceSetType = this.ResourceSetType, + Success = false, + Exception = ex + }); + } + } + + #endregion + + /// + /// Creates a new instance. + /// + /// Name of the resource + /// Path to retrieve the files from + /// Format of the file name using {{resource}} and {{culture}} placeholders. + public FileBasedResourceManager(string name, string path, string fileformat) + : base() + { + this.path = path; + this.fileformat = fileformat; + this.BaseNameField = name; + + base.IgnoreCase = false; + base.ResourceSets = new System.Collections.Hashtable(); + } + + protected override string GetResourceFileName(System.Globalization.CultureInfo culture) + { + return fileformat.Replace("{{culture}}", culture.Name).Replace("{{resource}}", BaseNameField); + } + + protected override System.Resources.ResourceSet InternalGetResourceSet(System.Globalization.CultureInfo culture, bool createIfNotExists, bool tryParents) + { + if (path == null && fileformat == null) return null; + if (culture == null || culture.Equals(CultureInfo.InvariantCulture)) return null; + + System.Resources.ResourceSet rs = null; + Hashtable resourceSets = this.ResourceSets; + + if (!TryFetchResourceSet(resourceSets, culture, out rs)) + { + string resourceFileName = this.FindResourceFile(culture); + if (resourceFileName == null) + { + if (tryParents) + { + CultureInfo parent = culture.Parent; + rs = this.InternalGetResourceSet(parent, createIfNotExists, tryParents); + AddResourceSet(resourceSets, culture, ref rs); + return rs; + } + } + else + { + rs = this.CreateResourceSet(resourceFileName); + AddResourceSet(resourceSets, culture, ref rs); + return rs; + } + } + + return rs; + } + + protected virtual System.Resources.ResourceSet InternalCreateResourceSet(string resourceFileName) + { + object[] args = new object[] { resourceFileName }; + return (System.Resources.ResourceSet)Activator.CreateInstance(this.ResourceSetType, args); + } + + private System.Resources.ResourceSet CreateResourceSet(string resourceFileName) + { + System.Resources.ResourceSet set = null; + + try + { + set = InternalCreateResourceSet(resourceFileName); + RaiseCreatedResourceSet(resourceFileName, set); + } + catch (Exception ex) + { + RaiseFailedResourceSet(resourceFileName, ex); + } + + return set; + } + + private string FindResourceFile(CultureInfo culture) + { + string resourceFileName = this.GetResourceFileName(culture); + string path = this.path ?? String.Empty; + + // Try with simple path + filename combination + string fullpath = System.IO.Path.Combine(path, resourceFileName); + if (File.Exists(fullpath)) return fullpath; + + // If path is relative, attempt different directories + if (path == String.Empty || !System.IO.Path.IsPathRooted(path)) + { + // Try the entry assembly dir + if (Assembly.GetEntryAssembly() != null) + { + string dir = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), path); + fullpath = System.IO.Path.Combine(dir, resourceFileName); + if (File.Exists(fullpath)) return fullpath; + } + + // Else try the executing assembly dir + if (Assembly.GetExecutingAssembly() != null) + { + if (Assembly.GetEntryAssembly() == null || System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) != System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)) + { + string dir = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), path); + fullpath = System.IO.Path.Combine(dir, resourceFileName); + if (File.Exists(fullpath)) return fullpath; + } + } + } + + return null; + } + + private void AddResourceSet(Hashtable localResourceSets, CultureInfo culture, ref System.Resources.ResourceSet rs) + { + lock (localResourceSets) + { + if (localResourceSets.Contains(culture)) + { + var existing = (System.Resources.ResourceSet)localResourceSets[culture]; + + if (existing != null && !object.Equals(existing, rs)) + { + rs.Dispose(); + rs = existing; + var a = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings"); + } + } + else + { + localResourceSets.Add(culture, rs); + } + } + } + + private bool TryFetchResourceSet(Hashtable localResourceSets, CultureInfo culture, out System.Resources.ResourceSet set) + { + lock (localResourceSets) + { + if (ResourceSets.Contains(culture)) + { + set = (System.Resources.ResourceSet)ResourceSets[culture]; + return true; + } + + set = null; + return false; + } + } + + private bool ValidateGetResourceSet(CultureInfo culture) + { + return !(culture == null || culture.Equals(CultureInfo.InvariantCulture) || String.IsNullOrEmpty(culture.Name)); + } + + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/GettextResourceManager.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/GettextResourceManager.cs new file mode 100644 index 00000000..3d62b376 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/GettextResourceManager.cs @@ -0,0 +1,150 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using System.Reflection; +using System.Diagnostics; +using System.Globalization; +using System.Configuration; +using System.Collections.Specialized; +using System.Security.Permissions; +using System.Collections; + +namespace Gettext.Cs +{ + /// + /// Gettext based resource manager that reads from po files. + /// + public class GettextResourceManager : FileBasedResourceManager + { + #region Defaults + + const string defaultFileFormat = "{{culture}}\\{{resource}}.po"; + const string defaultPath = ""; + + #endregion + + #region Properties + + /// + /// Returns the Gettext resource set type used. + /// + public override Type ResourceSetType + { + get { return typeof(GettextResourceSet); } + } + + #endregion + + #region Constructos + + /// + /// Creates a new instance. + /// + /// Name of the resource + /// Path to retrieve the files from + /// Format of the file name using {{resource}} and {{culture}} placeholders. + public GettextResourceManager(string name, string path, string fileformat) + : base(name, path, fileformat) + { + } + + /// + /// Creates a new instance using local path and "{{culture}}\{{resource}}.po" file format. + /// + /// Name of the resource + public GettextResourceManager(string name) + : base(name, defaultPath, defaultFileFormat) + { + } + + #endregion + + #region Configuration + + /// + /// Loads the named configuration section and retrieves file format and path from "fileformat" and "path" settings. + /// + /// Name of the section to retrieve. + /// True if the configuration section was loaded. + public bool LoadConfiguration(string section) + { + var config = ConfigurationManager.GetSection(section) as NameValueCollection; + + if (config == null) return false; + + this.FileFormat = config["fileformat"] ?? FileFormat; + this.Path = config["path"] ?? Path; + + return true; + } + + /// + /// Creates a new instance retrieving path and fileformat from the specified configuration section. + /// + /// Name of the resource + /// Name of the configuration section + /// New instance of ResourceManager + public static FileBasedResourceManager CreateFromConfiguration(string name, string section) + { + return CreateFromConfiguration(name, section, defaultFileFormat, defaultPath); + } + + /// + /// Creates a new instance retrieving path and fileformat from the specified configuration section. + /// + /// Name of the resource + /// Name of the configuration section with fileformat and path settings + /// File format to be used if configuration could not be retrieved + /// Path to be used if configuration could not be retrieved + /// New instance of ResourceManager + public static FileBasedResourceManager CreateFromConfiguration(string name, string section, string fallbackFileFormat, string fallbackPath) + { + var config = ConfigurationManager.GetSection(section) as NameValueCollection; + + string fileformat = null; + string path = null; + + if (config == null) + { + fileformat = fallbackFileFormat; + path = fallbackPath; + } + else + { + fileformat = config["fileformat"] ?? fallbackFileFormat; + path = config["path"] ?? fallbackPath; + } + + return new FileBasedResourceManager(name, path, fileformat); + } + + #endregion + + } + + +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/GettextResourceReader.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/GettextResourceReader.cs new file mode 100644 index 00000000..dc3a0b7e --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/GettextResourceReader.cs @@ -0,0 +1,87 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Resources; +using System.IO; + +namespace Gettext.Cs +{ + public class GettextResourceReader : IResourceReader + { + Stream stream; + + public GettextResourceReader(Stream stream) + { + this.stream = stream; + } + + #region IResourceReader Members + + public void Close() + { + if (stream != null) + { + this.stream.Close(); + } + } + + public System.Collections.IDictionaryEnumerator GetEnumerator() + { + if (stream == null) + { + throw new ArgumentNullException("Input stream cannot be null"); + } + + using (var reader = new StreamReader(stream)) + { + return new PoParser().ParseIntoDictionary(reader).GetEnumerator(); + } + } + + #endregion + + #region IEnumerable Members + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return this.GetEnumerator(); + } + + #endregion + + #region IDisposable Members + + public void Dispose() + { + if (stream != null) + { + stream.Dispose(); + } + } + + #endregion + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/GettextResourceSet.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/GettextResourceSet.cs new file mode 100644 index 00000000..614eb9c8 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Resource/GettextResourceSet.cs @@ -0,0 +1,49 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using System.Globalization; + +namespace Gettext.Cs +{ + public class GettextResourceSet : System.Resources.ResourceSet + { + public GettextResourceSet(string filename) + : base(new GettextResourceReader(File.OpenRead(filename))) + { + } + + public GettextResourceSet(Stream stream) + : base(new GettextResourceReader(stream)) + { + } + + public override Type GetDefaultReader() + { + return typeof(Gettext.Cs.GettextResourceReader); + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Templates/Strings.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Templates/Strings.cs new file mode 100644 index 00000000..64c9ec22 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Templates/Strings.cs @@ -0,0 +1,166 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +// +// This code was generated by a tool. Any changes made manually will be lost +// the next time this code is regenerated. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; +using System.Threading; +using System.Configuration; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +namespace Gettext +{ + public class Strings + { + private static Object resourceManLock = new Object(); + private static System.Resources.ResourceManager resourceMan; + private static System.Globalization.CultureInfo resourceCulture; + + public const string ResourceName = "Strings"; + + private static string resourcesDir = GetSetting("ResourcesDir", "Po"); + private static string fileFormat = GetSetting("ResourcesFileFormat", "{{culture}}/{{resource}}.po"); + + private static string GetSetting(string setting, string defaultValue) + { + var section = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings"); + if (section == null) return defaultValue; + else return section[setting] ?? defaultValue; + } + + + /// + /// Resources directory used to retrieve files from. + /// + public static string ResourcesDirectory + { + get { return resourcesDir; } + set { resourcesDir = value; } + } + + /// + /// Format of the file based on culture and resource name. + /// + public static string FileFormat + { + get { return fileFormat; } + set { fileFormat = value; } + } + + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + public static System.Resources.ResourceManager ResourceManager + { + get + { + + if (object.ReferenceEquals(resourceMan, null)) + { + lock (resourceManLock) + { + if (object.ReferenceEquals(resourceMan, null)) + { + var directory = resourcesDir; + var mgr = new global::Gettext.Cs.GettextResourceManager(ResourceName, directory, fileFormat); + resourceMan = mgr; + } + } + } + + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + public static System.Globalization.CultureInfo Culture + { + get { return resourceCulture; } + set { resourceCulture = value; } + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(string t) + { + return T(null, t); + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t) + { + if (String.IsNullOrEmpty(t)) return t; + var translated = ResourceManager.GetString(t, info ?? resourceCulture); + return String.IsNullOrEmpty(translated) ? t : translated; + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(string t, params object[] parameters) + { + return T(null, t, parameters); + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t, params object[] parameters) + { + if (String.IsNullOrEmpty(t)) return t; + return String.Format(T(info, t), parameters); + } + + /// + /// Marks a string for future translation, does not translate it now. + /// + public static string M(string t) + { + return t; + } + + /// + /// Returns the resource set available for the specified culture. + /// + public static System.Resources.ResourceSet GetResourceSet(CultureInfo culture) + { + return ResourceManager.GetResourceSet(culture, true, true); + } + } +} + diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Templates/Strings.tt b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Templates/Strings.tt new file mode 100644 index 00000000..88ff36c8 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Core/Gettext.Cs/Templates/Strings.tt @@ -0,0 +1,196 @@ +<#@ template language="C#v3.5" hostspecific="True" #> +// +// This code was generated by a tool. Any changes made manually will be lost +// the next time this code is regenerated. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; +using System.Threading; +using System.Configuration; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +namespace <#= this.NamespaceName #> +{ + public class <#= this.ClassName #> + { + private static Object resourceManLock = new Object(); + private static System.Resources.ResourceManager resourceMan; + private static System.Globalization.CultureInfo resourceCulture; + + public const string ResourceName = "<#= this.ResourceName #>"; + +<# if (!UseDatabase) { #> + private static string resourcesDir = GetSetting("ResourcesDir", "<#= this.DefaultResourceDir #>"); + private static string fileFormat = GetSetting("ResourcesFileFormat", "<#= this.DefaultFileFormat #>"); +<# } #> + + private static string GetSetting(string setting, string defaultValue) + { + var section = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("<#= this.ConfigurationSection #>"); + if (section == null) return defaultValue; + else return section[setting] ?? defaultValue; + } + +<# if (!UseDatabase) { #> + /// + /// Resources directory used to retrieve files from. + /// + public static string ResourcesDirectory + { + get { return resourcesDir; } + set { resourcesDir = value; } + } + + /// + /// Format of the file based on culture and resource name. + /// + public static string FileFormat + { + get { return fileFormat; } + set { fileFormat = value; } + } +<# } #> + +<# if (ResourceManagerExpires) { #> + private static DateTime resourceManagerLoadedAt = DateTime.Now; +<# } #> + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + public static System.Resources.ResourceManager ResourceManager + { + get + { +<# if (ResourceManagerExpires) { #> + if (resourceMan != null && DateTime.Now.Subtract(resourceManagerLoadedAt).TotalMinutes >= <#= ResourceManagerTTL #>) + { + lock (resourceManLock) + { + if (resourceMan != null && DateTime.Now.Subtract(resourceManagerLoadedAt).TotalMinutes >= <#= ResourceManagerTTL #>) + { + resourceMan.ReleaseAllResources(); + resourceMan = null; + } + } + } +<# } #> + + if (object.ReferenceEquals(resourceMan, null)) + { + lock (resourceManLock) + { + if (object.ReferenceEquals(resourceMan, null)) + { +<# if (UseDatabase) { #> + var mgr = new global::Gettext.Cs.DatabaseResourceManager("<#= this.StoredProcedureName #>"); +<# } else { #> + var directory = resourcesDir; + <# if (ServerMapPath) { #> + if (System.Web.HttpContext.Current != null) + directory = System.Web.HttpContext.Current.Server.MapPath(directory); + <# } #> + var mgr = <#= String.Format(this.ResourceManagerCtor, this.ResourceManagerType) #>; + <# if (ResourceManagerExpires) { #> + resourceManagerLoadedAt = DateTime.Now; + <# } #> +<# } #> + resourceMan = mgr; + } + } + } + + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + public static System.Globalization.CultureInfo Culture + { + get { return resourceCulture; } + set { resourceCulture = value; } + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(string t) + { + return T(null, t); + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t) + { + if (String.IsNullOrEmpty(t)) return t; + var translated = ResourceManager.GetString(t, info ?? resourceCulture); + return String.IsNullOrEmpty(translated) ? t : translated; + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(string t, params object[] parameters) + { + return T(null, t, parameters); + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t, params object[] parameters) + { + if (String.IsNullOrEmpty(t)) return t; + return String.Format(T(info, t), parameters); + } + + /// + /// Marks a string for future translation, does not translate it now. + /// + public static string M(string t) + { + return t; + } + + /// + /// Returns the resource set available for the specified culture. + /// + public static System.Resources.ResourceSet GetResourceSet(CultureInfo culture) + { + return ResourceManager.GetResourceSet(culture, true, true); + } + } +} + +<#+ + // Template parameters + + string ClassName = "Strings"; + string ResourceName = "Strings"; + string NamespaceName = "Gettext"; + + string ResourceManagerType = "global::Gettext.Cs.GettextResourceManager"; + string ResourceManagerCtor = "new {0}(ResourceName, directory, fileFormat)"; + string DefaultResourceDir = "Po"; + string DefaultFileFormat = "{{culture}}/{{resource}}.po"; + + string ConfigurationSection = "appSettings"; + bool ServerMapPath = false; + + bool ResourceManagerExpires = false; + int ResourceManagerTTL = 0; + + bool UseDatabase = false; + string StoredProcedureName = "GettextGetResourceSet"; +#> diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Gettext.CsUtils.sln b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Gettext.CsUtils.sln new file mode 100644 index 00000000..b1d2c6bd --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Gettext.CsUtils.sln @@ -0,0 +1,125 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{FD8EF9F6-9B97-456A-98E0-E94DB2BD3EED}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{64737816-54EF-4891-A58D-0642F07F09AD}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gnu.Getopt", "Lib\Gnu.Getopt\Gnu.Getopt.csproj", "{379BC478-7D84-4E0E-A4B8-197905C824AE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.AspExtract", "Tools\Gettext.AspExtract\Gettext.AspExtract.csproj", "{88A09FE2-5DE0-4C6E-9C4C-BB5E8A490CF5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.Msgfmt", "Tools\Gettext.Msgfmt\Gettext.Msgfmt.csproj", "{F72A7CBA-E656-4ECA-97F9-2B601E0BCDF9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.ResourcesReplacer", "Tools\Gettext.ResourcesReplacer\Gettext.ResourcesReplacer.csproj", "{11BDD346-EDFA-439D-A42D-A1D4FDB64C9A}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{380A3584-88CB-4153-9BC1-C18CFAE9EF26}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.Cs", "Core\Gettext.Cs\Gettext.Cs.csproj", "{D8869765-AB47-4C03-B2C5-E5498A55CA79}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gnu.Gettext", "Lib\Gnu.Gettext\Gnu.Gettext.csproj", "{859A653A-7728-4F02-BAF2-A5CD8F991916}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.Cs.Web", "Core\Gettext.Cs.Web\Gettext.Cs.Web.csproj", "{38474466-DA21-4D19-A4D8-E2E7918480D6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.DatabaseResourceGenerator", "Tools\Gettext.DatabaseResourceGenerator\Gettext.DatabaseResourceGenerator.csproj", "{B19D8863-C5C2-4A13-B24A-566EB7498D17}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{DF21B331-8022-4958-AEF7-D7897814038A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.Samples.Console", "Samples\Gettext.Samples.Console\Gettext.Samples.Console.csproj", "{470FDBA5-04E5-4A9F-80EA-987D1F8D9074}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.Cs.Tests", "Core\Gettext.Cs.Tests\Gettext.Cs.Tests.csproj", "{C4B4300B-5B96-4F43-BD7D-517A29693B30}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.Iconv", "Tools\Gettext.Iconv\Gettext.Iconv.csproj", "{7578444A-E104-4D72-94B5-DDCB1DA0D63F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.Samples.Mvc", "Samples\Gettext.Samples.Mvc\Gettext.Samples.Mvc.csproj", "{208D43F3-84E6-45B9-B6CC-6E3F48E42A82}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.Samples.Database", "Samples\Gettext.Samples.Database\Gettext.Samples.Database.csproj", "{9FBD5BA7-BCE6-48FE-9FB7-396F377D1313}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gettext.Samples.Spanish", "Samples\Gettext.Samples.Spanish\Gettext.Samples.Spanish.csproj", "{7404A86D-53FA-4B1B-B6FC-D84EB6F5E2D5}" +EndProject +Global + GlobalSection(TestCaseManagementSettings) = postSolution + CategoryFile = Gettext.CsUtils.vsmdi + EndGlobalSection + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {379BC478-7D84-4E0E-A4B8-197905C824AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {379BC478-7D84-4E0E-A4B8-197905C824AE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {379BC478-7D84-4E0E-A4B8-197905C824AE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {379BC478-7D84-4E0E-A4B8-197905C824AE}.Release|Any CPU.Build.0 = Release|Any CPU + {88A09FE2-5DE0-4C6E-9C4C-BB5E8A490CF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {88A09FE2-5DE0-4C6E-9C4C-BB5E8A490CF5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {88A09FE2-5DE0-4C6E-9C4C-BB5E8A490CF5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {88A09FE2-5DE0-4C6E-9C4C-BB5E8A490CF5}.Release|Any CPU.Build.0 = Release|Any CPU + {F72A7CBA-E656-4ECA-97F9-2B601E0BCDF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F72A7CBA-E656-4ECA-97F9-2B601E0BCDF9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F72A7CBA-E656-4ECA-97F9-2B601E0BCDF9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F72A7CBA-E656-4ECA-97F9-2B601E0BCDF9}.Release|Any CPU.Build.0 = Release|Any CPU + {11BDD346-EDFA-439D-A42D-A1D4FDB64C9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {11BDD346-EDFA-439D-A42D-A1D4FDB64C9A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {11BDD346-EDFA-439D-A42D-A1D4FDB64C9A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {11BDD346-EDFA-439D-A42D-A1D4FDB64C9A}.Release|Any CPU.Build.0 = Release|Any CPU + {D8869765-AB47-4C03-B2C5-E5498A55CA79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D8869765-AB47-4C03-B2C5-E5498A55CA79}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D8869765-AB47-4C03-B2C5-E5498A55CA79}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D8869765-AB47-4C03-B2C5-E5498A55CA79}.Release|Any CPU.Build.0 = Release|Any CPU + {859A653A-7728-4F02-BAF2-A5CD8F991916}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {859A653A-7728-4F02-BAF2-A5CD8F991916}.Debug|Any CPU.Build.0 = Debug|Any CPU + {859A653A-7728-4F02-BAF2-A5CD8F991916}.Release|Any CPU.ActiveCfg = Release|Any CPU + {859A653A-7728-4F02-BAF2-A5CD8F991916}.Release|Any CPU.Build.0 = Release|Any CPU + {38474466-DA21-4D19-A4D8-E2E7918480D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {38474466-DA21-4D19-A4D8-E2E7918480D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {38474466-DA21-4D19-A4D8-E2E7918480D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {38474466-DA21-4D19-A4D8-E2E7918480D6}.Release|Any CPU.Build.0 = Release|Any CPU + {B19D8863-C5C2-4A13-B24A-566EB7498D17}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B19D8863-C5C2-4A13-B24A-566EB7498D17}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B19D8863-C5C2-4A13-B24A-566EB7498D17}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B19D8863-C5C2-4A13-B24A-566EB7498D17}.Release|Any CPU.Build.0 = Release|Any CPU + {470FDBA5-04E5-4A9F-80EA-987D1F8D9074}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {470FDBA5-04E5-4A9F-80EA-987D1F8D9074}.Debug|Any CPU.Build.0 = Debug|Any CPU + {470FDBA5-04E5-4A9F-80EA-987D1F8D9074}.Release|Any CPU.ActiveCfg = Release|Any CPU + {470FDBA5-04E5-4A9F-80EA-987D1F8D9074}.Release|Any CPU.Build.0 = Release|Any CPU + {C4B4300B-5B96-4F43-BD7D-517A29693B30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C4B4300B-5B96-4F43-BD7D-517A29693B30}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C4B4300B-5B96-4F43-BD7D-517A29693B30}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C4B4300B-5B96-4F43-BD7D-517A29693B30}.Release|Any CPU.Build.0 = Release|Any CPU + {7578444A-E104-4D72-94B5-DDCB1DA0D63F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7578444A-E104-4D72-94B5-DDCB1DA0D63F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7578444A-E104-4D72-94B5-DDCB1DA0D63F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7578444A-E104-4D72-94B5-DDCB1DA0D63F}.Release|Any CPU.Build.0 = Release|Any CPU + {208D43F3-84E6-45B9-B6CC-6E3F48E42A82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {208D43F3-84E6-45B9-B6CC-6E3F48E42A82}.Debug|Any CPU.Build.0 = Debug|Any CPU + {208D43F3-84E6-45B9-B6CC-6E3F48E42A82}.Release|Any CPU.ActiveCfg = Release|Any CPU + {208D43F3-84E6-45B9-B6CC-6E3F48E42A82}.Release|Any CPU.Build.0 = Release|Any CPU + {9FBD5BA7-BCE6-48FE-9FB7-396F377D1313}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9FBD5BA7-BCE6-48FE-9FB7-396F377D1313}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9FBD5BA7-BCE6-48FE-9FB7-396F377D1313}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9FBD5BA7-BCE6-48FE-9FB7-396F377D1313}.Release|Any CPU.Build.0 = Release|Any CPU + {7404A86D-53FA-4B1B-B6FC-D84EB6F5E2D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7404A86D-53FA-4B1B-B6FC-D84EB6F5E2D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7404A86D-53FA-4B1B-B6FC-D84EB6F5E2D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7404A86D-53FA-4B1B-B6FC-D84EB6F5E2D5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {88A09FE2-5DE0-4C6E-9C4C-BB5E8A490CF5} = {FD8EF9F6-9B97-456A-98E0-E94DB2BD3EED} + {F72A7CBA-E656-4ECA-97F9-2B601E0BCDF9} = {FD8EF9F6-9B97-456A-98E0-E94DB2BD3EED} + {11BDD346-EDFA-439D-A42D-A1D4FDB64C9A} = {FD8EF9F6-9B97-456A-98E0-E94DB2BD3EED} + {B19D8863-C5C2-4A13-B24A-566EB7498D17} = {FD8EF9F6-9B97-456A-98E0-E94DB2BD3EED} + {7578444A-E104-4D72-94B5-DDCB1DA0D63F} = {FD8EF9F6-9B97-456A-98E0-E94DB2BD3EED} + {379BC478-7D84-4E0E-A4B8-197905C824AE} = {64737816-54EF-4891-A58D-0642F07F09AD} + {859A653A-7728-4F02-BAF2-A5CD8F991916} = {64737816-54EF-4891-A58D-0642F07F09AD} + {D8869765-AB47-4C03-B2C5-E5498A55CA79} = {380A3584-88CB-4153-9BC1-C18CFAE9EF26} + {38474466-DA21-4D19-A4D8-E2E7918480D6} = {380A3584-88CB-4153-9BC1-C18CFAE9EF26} + {C4B4300B-5B96-4F43-BD7D-517A29693B30} = {380A3584-88CB-4153-9BC1-C18CFAE9EF26} + {470FDBA5-04E5-4A9F-80EA-987D1F8D9074} = {DF21B331-8022-4958-AEF7-D7897814038A} + {208D43F3-84E6-45B9-B6CC-6E3F48E42A82} = {DF21B331-8022-4958-AEF7-D7897814038A} + {9FBD5BA7-BCE6-48FE-9FB7-396F377D1313} = {DF21B331-8022-4958-AEF7-D7897814038A} + {7404A86D-53FA-4B1B-B6FC-D84EB6F5E2D5} = {DF21B331-8022-4958-AEF7-D7897814038A} + EndGlobalSection +EndGlobal diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/AssemblyInfo.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/AssemblyInfo.cs new file mode 100644 index 00000000..c22a6b26 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/AssemblyInfo.cs @@ -0,0 +1,88 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Permissions; + +// +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +// +[assembly: AssemblyTitle("GNU Getopt Argument Parser")] +[assembly: AssemblyDescription("This is a C# port of a Java port of GNU " + + "Getopt, a class for parsing command line arguments passed to programs. " + + "It is based on the C getopt() functions in glibc 2.0.6 and should " + + "parse options in a 100% compatible manner.")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Free Software Foundation, Inc.")] +[assembly: AssemblyProduct("GNU Getopt")] +[assembly: AssemblyCopyright("Copyright (c) 1987-1997 Free Software " + + "Foundation, Inc., Java Port Copyright (c) 1998 by Aaron M. Renn " + + "(arenn@urbanophile.com), C#.NET Port of the Java Port Copyright (c) " + + "2004 by Klaus Prückl (klaus.prueckl@aon.at)")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly: AssemblyVersion("0.9.1.*")] + +// +// In order to sign your assembly you must specify a key to use. Refer to the +// Microsoft .NET Framework documentation for more information on assembly signing. +// +// Use the attributes below to control which key is used for signing. +// +// Notes: +// (*) If no key is specified, the assembly is not signed. +// (*) KeyName refers to a key that has been installed in the Crypto Service +// Provider (CSP) on your machine. KeyFile refers to a file which contains +// a key. +// (*) If the KeyFile and the KeyName values are both specified, the +// following processing occurs: +// (1) If the KeyName can be found in the CSP, that key is used. +// (2) If the KeyName does not exist and the KeyFile does exist, the key +// in the KeyFile is installed into the CSP and used. +// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. +// When specifying the KeyFile, the location of the KeyFile should be +// relative to the project output directory which is +// %Project Directory%\obj\. For example, if your KeyFile is +// located in the project directory, you would specify the AssemblyKeyFile +// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] +// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework +// documentation for more information on this. +// +[assembly:CLSCompliant(true)] +[assembly:ComVisible(true)] \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/Getopt.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/Getopt.cs new file mode 100644 index 00000000..b159a172 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/Getopt.cs @@ -0,0 +1,1417 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +/************************************************************************** +/* Getopt.cs -- C#.NET port of Java port of GNU getopt from glibc 2.0.6 +/* +/* Copyright (c) 1987-1997 Free Software Foundation, Inc. +/* Java Port Copyright (c) 1998 by Aaron M. Renn (arenn@urbanophile.com) +/* C#.NET Port Copyright (c) 2004 by Klaus Prückl (klaus.prueckl@aon.at) +/* +/* This program is free software; you can redistribute it and/or modify +/* it under the terms of the GNU Library General Public License as published +/* by the Free Software Foundation; either version 2 of the License or +/* (at your option) any later version. +/* +/* This program is distributed in the hope that it will be useful, but +/* WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU Library General Public License for more details. +/* +/* You should have received a copy of the GNU Library General Public License +/* along with this program; see the file COPYING.LIB. If not, write to +/* the Free Software Foundation Inc., 59 Temple Place - Suite 330, +/* Boston, MA 02111-1307 USA +/**************************************************************************/ + +using System; +using System.Configuration; +using System.Globalization; +using System.Reflection; +using System.Resources; + +namespace Gnu.Getopt +{ + /// + /// This is a C# port of a Java port of GNU getopt, a class for parsing + /// command line arguments passed to programs. It it based on the C + /// getopt() functions in glibc 2.0.6 and should parse options in a 100% + /// compatible manner. If it does not, that is a bug. The programmer's + /// interface is also very compatible. + /// + /// + /// To use Getopt, create a Getopt object with a args array passed to the + /// main method, then call the method in a loop. It + /// will return an that contains the value of the option + /// character parsed from the command line. When there are no more options + /// to be parsed, it returns -1. + /// + /// A command line option can be defined to take an argument. If an option + /// has an argument, the value of that argument is stored in an instance + /// variable called optarg, which can be accessed using the + /// property. + /// If an option that requires an argument is found, but there is no + /// argument present, then an error message is printed. Normally + /// returns a '?' in this situation, but that + /// can be changed as described below. + /// + /// + /// If an invalid option is encountered, an error message is printed to + /// the standard error and returns a '?'. + /// The value of the invalid option encountered is stored in the instance + /// variable optopt which can be retrieved using the + /// property. + /// To suppress the printing of error messages for this or any other error, + /// set the value of the opterr instance variable to false using the + /// property. + /// + /// + /// Between calls to , the instance variable + /// optind is used to keep track of where the object is in the + /// parsing process. After all options have been returned, optind + /// is the index in argv of the first non-option argument. + /// This variable can be accessed with the property. + /// + /// + /// Note that this object expects command line options to be passed in the + /// traditional Unix manner. That is, proceeded by a '-' character. + /// Multiple options can follow the '-'. For example "-abc" + /// is equivalent to "-a -b -c". If an option takes a required + /// argument, the value of the argument can immediately follow the option + /// character or be present in the next argv element. For example, + /// "-cfoo" and "-c foo" both represent an option character + /// of 'c' with an argument of "foo" assuming c takes + /// a required argument. + /// If an option takes an argument that is not required, then any argument + /// must immediately follow the option character in the same argv element. + /// For example, if c takes a non-required argument, then "-cfoo" + /// represents option character 'c' with an argument of "foo" + /// while "-c foo" represents the option character 'c' with + /// no argument, and a first non-option argv element of "foo". + /// + /// + /// The user can stop from scanning any further into + /// a command line by using the special argument "--" by itself. + /// For example: + /// "-a -- -d" would return an option character of 'a', then + /// return -1. + /// The "--" is discarded and "-d" is pointed to by + /// optind as the first non-option argv element. + /// + /// + /// Here is a basic example of using Getopt: + /// + /// Getopt g = new Getopt("testprog", args, "ab:c::d"); + /// + /// int c; + /// string arg; + /// while ((c = g.getopt()) != -1) + /// { + /// switch(c) + /// { + /// case 'a': + /// case 'd': + /// Console.WriteLine("You picked " + (char)c ); + /// break; + /// + /// case 'b': + /// case 'c': + /// arg = g.Optarg; + /// Console.WriteLine("You picked " + (char)c + + /// " with an argument of " + + /// ((arg != null) ? arg : "null") ); + /// break; + /// + /// case '?': + /// break; // getopt() already printed an error + /// + /// default: + /// Console.WriteLine("getopt() returned " + c); + /// break; + /// } + /// } + /// + /// In this example, a new Getopt object is created with three params. The + /// first param is the program name. This is for printing error messages in + /// the form "program: error message". In the C version, this value is + /// taken from argv[0], but in .NET the program name is not passed in that + /// element, thus the need for this parameter. The second param is the + /// argument list that was passed to the main() method. The third param is + /// the list of valid options. Each character represents a valid option. If + /// the character is followed by a single colon, then that option has a + /// required argument. If the character is followed by two colons, then + /// that option has an argument that is not required. + /// + /// Note in this example that the value returned from + /// is cast to a char prior to printing. This is required in order to make + /// the value display correctly as a character instead of an integer. + /// + /// + /// If the first character in the option string is a colon, for example + /// ":abc::d", then will return a ':' + /// instead of a '?' when it encounters an option with a missing + /// required argument. This allows the caller to distinguish between + /// invalid options and valid options that are simply incomplete. + /// + /// In the traditional Unix getopt(), -1 is returned when the first + /// non-option charcter is encountered. In GNU getopt(), the default + /// behavior is to allow options to appear anywhere on the command line. + /// The method permutes the argument to make it appear + /// to the caller that all options were at the beginning of the command + /// line, and all non-options were at the end. For example, calling + /// with command line argv of "-a foo bar -d" + /// returns options 'a' and 'd', then sets optind to point to + /// "foo". The program would read the last two argv elements as + /// "foo" and "bar", just as if the user had typed + /// "-a -d foo bar". + /// + /// + /// The user can force to stop scanning the command + /// line with the special argument "--" by itself. Any elements + /// occuring before the "--" are scanned and permuted as normal. Any + /// elements after the "--" are returned as is as non-option argv + /// elements. For example, "foo -a -- bar -d" would return option + /// 'a' then -1. optind would point to "foo", + /// "bar" and "-d" as the non-option argv elements. The + /// "--" is discarded by . + /// + /// + /// There are two ways this default behavior can be modified. The first is + /// to specify traditional Unix getopt() behavior (which is also POSIX + /// behavior) in which scanning stops when the first non-option argument + /// encountered. (Thus "-a foo bar -d" would return 'a' as an + /// option and have "foo", "bar", and "-d" as + /// non-option elements). + /// The second is to allow options anywhere, but to return all elements in + /// the order they occur on the command line. + /// When a non-option element is ecountered, an integer 1 is returned and + /// the value of the non-option element is stored in optarg is if + /// it were the argument to that option. + /// For example, "-a foo -d", returns first 'a', then 1 (with + /// optarg set to "foo") then 'd' then -1. + /// When this "return in order" functionality is enabled, the only way to + /// stop getopt from scanning all command line elements is to + /// use the special "--" string by itself as described above. An + /// example is "-a foo -b -- bar", which would return 'a', + /// then integer 1 with optarg set to "foo", then 'b', + /// then -1. + /// optind would then point to "bar" as the first non-option + /// argv element. The "--" is discarded. + /// + /// + /// The POSIX/traditional behavior is enabled by either setting the + /// application setting "Gnu.PosixlyCorrect" or by putting a '+' + /// sign as the first character of the option string. + /// The difference between the two methods is that setting the + /// "Gnu.PosixlyCorrect" application setting also forces certain error + /// messages to be displayed in POSIX format. + /// To enable the "return in order" functionality, put a '-' as the + /// first character of the option string. Note that after determining the + /// proper behavior, Getopt strips this leading '+' or '-', + /// meaning that a ':' placed as the second character after one of + /// those two will still cause to return a ':' + /// instead of a '?' if a required option argument is missing. + /// + /// + /// In addition to traditional single character options, GNU Getopt also + /// supports long options. These are preceeded by a "--" sequence + /// and can be as long as desired. Long options provide a more + /// user-friendly way of entering command line options. + /// For example, in addition to a "-h" for help, a program could + /// support also "--help". + /// + /// + /// Like short options, long options can also take a required or + /// non-required argument. Required arguments can either be specified by + /// placing an equals sign after the option name, then the argument, or by + /// putting the argument in the next argv element. For example: + /// "--outputdir=foo" and "--outputdir foo" both represent an + /// option of "outputdir" with an argument of "foo", assuming + /// that outputdir takes a required argument. If a long option takes a + /// non-required argument, then the equals sign form must be used to + /// specify the argument. In this case, "--outputdir=foo" would + /// represent option outputdir with an argument of foo while + /// "--outputdir foo" would represent the option outputdir with no + /// argument and a first non-option argv element of "foo". + /// + /// + /// Long options can also be specified using a special POSIX argument + /// format (one that I highly discourage). This form of entry is enabled by + /// placing a "W;" (yes, 'W' then a semi-colon) in the valid + /// option string. + /// This causes getopt to treat the name following the "-W" as the + /// name of the long option. For example, "-W outputdir=foo" would + /// be equivalent to "--outputdir=foo". The name can immediately + /// follow the "-W" like so: "-Woutputdir=foo". + /// Option arguments are handled identically to normal long options. If a + /// string follows the "-W" that does not represent a + /// valid long option, then returns 'W' and + /// the caller must decide what to do. Otherwise + /// returns a long option value as described below. + /// + /// + /// While long options offer convenience, they can also be tedious to type + /// in full. So it is permissible to abbreviate the option name to as few + /// characters as required to uniquely identify it. If the name can + /// represent multiple long options, then an error message is printed and + /// returns a '?'. + /// + /// + /// If an invalid option is specified or a required option argument is + /// missing, prints an error and returns a '?' + /// or ':' exactly as for short options. + /// Note that when an invalid long option is encountered, the optopt + /// variable is set to integer 0 and so cannot be used to identify the + /// incorrect option the user entered. + /// + /// + /// Long options are defined by objects. These + /// objects are created with a contructor that takes four params: a string + /// representing the object name, a integer specifying what arguments the + /// option takes (the value is one of the + /// enumeration: , + /// , or ), + /// a flag object (described + /// below), and an integer value (described below). + /// + /// + /// To enable long option parsing, create an array of + /// 's representing the legal options and pass it to + /// the Getopt() constructor. + /// WARNING: If all elements of the array are not populated with + /// objects, the method will + /// throw a . + /// + /// + /// When is called and a long option is encountered, + /// one of two things can be returned. + /// If the flag field in the object representing the + /// long option is non-null, then the integer value field is stored there + /// and an integer 0 is returned to the caller. + /// The val field can then be retrieved from the flag field. + /// Note that since the flag field is a + /// , the appropriate string to + /// integer converions must be performed in order to get the actual int + /// value stored there. + /// If the flag field in the object is null, + /// then the value field of the is returned. + /// This can be the character of a short option. + /// This allows an app to have both a long and short option sequence (say, + /// "-h" and "--help") that do the exact same thing. + /// + /// + /// With long options, there is an alternative method of determining which + /// option was selected. The property Longind will return the index in the + /// long option array (NOT argv) of the long option found. So if multiple + /// long options are configured to return the same value, the application + /// can use to distinguish between them. + /// + /// + /// Here is an expanded Getopt example using long options and various + /// techniques described above: + /// + /// int c; + /// string arg; + /// LongOpt[] longopts = new LongOpt[3]; + /// + /// StringBuffer sb = new StringBuffer(); + /// longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'); + /// longopts[1] = new LongOpt("outputdir", LongOpt.REQUIRED_ARGUMENT, sb, 'o'); + /// longopts[2] = new LongOpt("maximum", LongOpt.OPTIONAL_ARGUMENT, null, 2); + /// + /// Getopt g = new Getopt("testprog", argv, "-:bc::d:hW;", longopts); + /// g.Opterr = false; // We'll do our own error handling + /// + /// while ((c = g.getopt()) != -1) + /// switch (c) + /// { + /// case 0: + /// arg = g.getOptarg(); + /// Console.WriteLine("Got long option with value '" + + /// (char)(new Integer(sb.toString())).intValue() + /// + "' with argument " + + /// ((arg != null) ? arg : "null")); + /// break; + /// + /// case 1: + /// Console.WriteLine("I see you have return in order set and that " + + /// "a non-option argv element was just found " + + /// "with the value '" + g.Optarg + "'"); + /// break; + /// + /// case 2: + /// arg = g.getOptarg(); + /// Console.WriteLine("I know this, but pretend I didn't"); + /// Console.WriteLine("We picked option " + + /// longopts[g.Longind].getName() + + /// " with value " + + /// ((arg != null) ? arg : "null")); + /// break; + /// + /// case 'b': + /// Console.WriteLine("You picked plain old option " + (char)c); + /// break; + /// + /// case 'c': + /// case 'd': + /// arg = g.getOptarg(); + /// Console.WriteLine("You picked option '" + (char)c + + /// "' with argument " + + /// ((arg != null) ? arg : "null")); + /// break; + /// + /// case 'h': + /// Console.WriteLine("I see you asked for help"); + /// break; + /// + /// case 'W': + /// Console.WriteLine("Hmmm. You tried a -W with an incorrect long " + + /// "option name"); + /// break; + /// + /// case ':': + /// Console.WriteLine("Doh! You need an argument for option " + + /// (char)g.getOptopt()); + /// break; + /// + /// case '?': + /// Console.WriteLine("The option '" + (char)g.getOptopt() + + /// "' is not valid"); + /// break; + /// + /// default: + /// Console.WriteLine("getopt() returned " + c); + /// break; + /// } + /// + /// for (int i = g.getOptind(); i < argv.length ; i++) + /// Console.WriteLine("Non option argv element: " + argv[i] ); + /// + /// + /// There is an alternative form of the constructor used for long options + /// above. This takes a trailing boolean flag. If set to false, Getopt + /// performs identically to the example, but if the boolean flag is true + /// then long options are allowed to start with a single '-' instead + /// of "--". If the first character of the option is a valid short + /// option character, then the option is treated as if it were the short + /// option. Otherwise it behaves as if the option is a long option. + /// Note that the name given to this option - longOnly - is very + /// counter-intuitive. + /// It does not cause only long options to be parsed but instead enables + /// the behavior described above. + /// + /// + /// + /// Note that the functionality and variable names used are driven from the + /// C lib version as this object is a port of the C code, not a new + /// implementation. This should aid in porting existing C/C++ code, as well + /// as helping programmers familiar with the glibc version to adapt to the + /// C#.NET version. + /// + /// + /// Roland McGrath (roland@gnu.ai.mit.edu) + /// Ulrich Drepper (drepper@cygnus.com) + /// Aaron M. Renn (arenn@urbanophile.com) + /// Klaus Prückl (klaus.prueckl@aon.at) + /// LongOpt + public class Getopt + { + /// + /// Describe how to deal with options that follow non-option + /// ARGV-elements. + /// + /// If the caller did not specify anything, the default is RequireOrder + /// if the application setting Gnu.PosixlyCorrect is defined, Permute + /// otherwise. + /// + /// The special argument "--" forces an end of option-scanning + /// regardless of the value of ordering. In the case of + /// ReturnInOrder, only -- can cause to + /// return -1 with optind != argv.Length. + /// + private enum Order + { + /// + /// RequireOrder means don't recognize them as options; stop option + /// processing when the first non-option is seen. This is what Unix + /// does. This mode of operation is selected by either setting the + /// application setting Gnu.PosixlyCorrect, or using '+' as + /// the first character of the list of option characters. + /// + RequireOrder = 1, + /// + /// Permute is the default. We permute the contents of ARGV as we + /// scan, so that eventually all the non-options are at the end. + /// This allows options to be given in any order, even with + /// programs that were not written to expect this. + /// + Permute = 2, + /// + /// ReturnInOrder is an option available to programs that were + /// written to expect options and other ARGV-elements in any order + /// and that care about the ordering of the two. We describe each + /// non-option ARGV-element as if it were the argument of an option + /// with character code 1. Using '-' as the first character + /// of the list of option characters selects this mode of + /// operation. + /// + ReturnInOrder = 3 + } + + #region Instance Variables + /// + /// For communication from to the caller. When + /// finds an option that takes an argument, the + /// argument value is returned here. Also, when ordering is + /// , each non-option ARGV-element is + /// returned here. + /// + private string optarg; + + /// + /// Index in ARGV of the next element to be scanned. This is used for + /// communication to and from the caller and for communication between + /// successive calls to . + /// + /// On entry to , zero means this is the first + /// call; initialize. + /// + /// When returns -1, this is the index of the + /// first of the non-option elements that the caller should itself + /// scan. + /// + /// Otherwise, communicates from one call to the + /// next how much of ARGV has been scanned so far. + /// + private int optind = 0; + + /// + /// Callers store false here to inhibit the error message for + /// unrecognized options. + /// + private bool opterr = true; + + /// + /// When an unrecognized option is encountered, getopt will return a + /// '?' and store the value of the invalid option here. + /// + private int optopt = '?'; + + /// + /// The next char to be scanned in the option-element in which the last + /// option character we returned was found. This allows us to pick up + /// the scan where we left off. + /// + /// If this is zero, or a null string, it means resume the scan by + /// advancing to the next ARGV-element. + /// + private string nextchar; + + /// + /// This is the string describing the valid short options. + /// + private string optstring; + + /// + /// This is an array of objects which describ the + /// valid long options. + /// + private LongOpt[] longOptions; + + /// + /// This flag determines whether or not we are parsing only long args. + /// + private bool longOnly; + + /// + /// Stores the index into the longOptions array of the long + /// option found. + /// + private int longind; + + /// + /// The flag determines whether or not we operate in strict POSIX + /// compliance. + /// + private bool posixlyCorrect; + + /// + /// A flag which communicates whether or not + /// did all necessary processing for the + /// current option. + /// + private bool longoptHandled; + + /// + /// The index of the first non-option in argv[]. + /// + private int firstNonopt = 1; + + /// + /// The index of the last non-option in argv[]. + /// + private int lastNonopt = 1; + + /// + /// Flag to tell to immediately return -1 the next + /// time it is called. + /// + private bool endparse = false; + + /// + /// Saved argument list passed to the program. + /// + private string[] argv; + + /// + /// Determines whether we permute arguments or not. + /// + private Order ordering; + + /// + /// Name to print as the program name in error messages. This is + /// necessary since .NET does not place the program name in args[0]. + /// + private string progname; + + /// + /// The localized strings are kept in the resources, which can be + /// accessed by the class. + /// + private ResourceManager resManager = new ResourceManager( + "Gnu.Getopt.MessagesBundle", Assembly.GetExecutingAssembly()); + + /// + /// The current UI culture (set to en-US when posixly correctness is + /// enabled). + /// + private CultureInfo cultureInfo = CultureInfo.CurrentUICulture; + + #endregion + + #region Constructors + /// + /// Construct a basic Getopt instance with the given input data. Note + /// that this handles short options only. + /// + /// + /// The name to display as the program name when printing errors. + /// + /// + /// The string array passed as the command line to the program. + /// + /// + /// A string containing a description of the valid args for this + /// program. + /// + public Getopt(string progname, string[] argv, string optstring) : + this(progname, argv, optstring, null, false) + { + } + + /// + /// Construct a Getopt instance with given input data that is capable + /// of parsing long options as well as short. + /// + /// + /// The name to display as the program name when printing errors. + /// + /// + /// The string array passed as the command ilne to the program. + /// + /// + /// A string containing a description of the valid short args for this + /// program. + /// + /// + /// An array of objects that describes the valid + /// long args for this program. + /// + public Getopt(string progname, string[] argv, string optstring, + LongOpt[] longOptions) : this(progname, argv, optstring, + longOptions, false) + { + } + + /// + /// Construct a Getopt instance with given input data that is capable + /// of parsing long options and short options. Contrary to what you + /// might think, the flag does not + /// determine whether or not we scan for only long arguments. Instead, + /// a value of true here allows long arguments to start with a + /// '-' instead of "--" unless there is a conflict with + /// a short option name. + /// + /// + /// The name to display as the program name when printing errors + /// + /// + /// The string array passed as the command ilne to the program. + /// + /// + /// A string containing a description of the valid short args for this + /// program. + /// + /// + /// An array of objects that describes the valid + /// long args for this program. + /// + /// + /// true if long options that do not conflict with short options can + /// start with a '-' as well as "--". + /// + public Getopt(string progname, string[] argv, string optstring, + LongOpt[] longOptions, bool longOnly) + { + if (optstring.Length == 0) + optstring = " "; + + // This function is essentially _getopt_initialize from GNU getopt + this.progname = progname; + this.argv = argv; + this.optstring = optstring; + this.longOptions = longOptions; + this.longOnly = longOnly; + + // Check for application setting "Gnu.PosixlyCorrect" to determine + // whether to strictly follow the POSIX standard. This replaces the + // "POSIXLY_CORRECT" environment variable in the C version + try + { + if((bool) new AppSettingsReader().GetValue( + "Gnu.PosixlyCorrect", typeof(bool))) + { + this.posixlyCorrect = true; + this.cultureInfo = new CultureInfo("en-US"); + } + else + this.posixlyCorrect = false; + } + catch(Exception) + { + this.posixlyCorrect = false; + } + + // Determine how to handle the ordering of options and non-options + if (optstring[0] == '-') + { + this.ordering = Order.ReturnInOrder; + if (optstring.Length > 1) + this.optstring = optstring.Substring(1); + } + else if (optstring[0] == '+') + { + this.ordering = Order.RequireOrder; + if (optstring.Length > 1) + this.optstring = optstring.Substring(1); + } + else if (this.posixlyCorrect) + { + this.ordering = Order.RequireOrder; + } + else + { + this.ordering = Order.Permute; // The normal default case + } + } + #endregion + + #region Instance Methods + /// + /// In GNU getopt, it is possible to change the string containg valid + /// options on the fly because it is passed as an argument to + /// each time. + /// In this version we do not pass the string on every call. + /// In order to allow dynamic option string changing, this method is + /// provided. + /// + public string Optstring + { + get { return this.optstring; } + set + { + if (value.Length == 0) + value = " "; + + this.optstring = value; + } + } + + /// + /// optind is the index in ARGV of the next element to be + /// scanned. This is used for communication to and from the caller and + /// for communication between successive calls to . + /// + /// When returns -1, this is the index of the + /// first of the non-option elements that the caller should itself + /// scan. + /// + /// Otherwise, optind communicates from one call to the next how + /// much of ARGV has been scanned so far. + /// + /// + /// This method allows the optind index to be set manually. + /// Normally this is not necessary (and incorrect usage of this method + /// can lead to serious lossage), but optind is a public symbol + /// in GNU getopt, so this method was added to allow it to be modified + /// by the caller if desired. + /// + public int Optind + { + get { return this.optind; } + set { this.optind = value; } + } + + /// + /// Since in GNU getopt() the argument vector is passed back in to the + /// function every time, the caller can swap out argv on the + /// fly. Since passing argv is not required in the .NET version, this + /// method allows the user to override argv. Note that incorrect use of + /// this method can lead to serious lossage. + /// + public string[] Argv + { + get { return this.argv; } + set { this.argv = value; } + } + + /// + /// For communication from to the caller. When + /// finds an option that takes an argument, the + /// argument value is returned here. Also, when ordering is + /// , each non-option ARGV-element is + /// returned here. No set method is provided because setting this + /// variable has no effect. + /// + public string Optarg + { + get { return this.optarg; } + } + + /// + /// Normally will print a message to the standard + /// error when an invalid option is encountered. This can be suppressed + /// (or re-enabled) by calling this method. + /// + public bool Opterr + { + get { return this.opterr; } + set { this.opterr = value; } + } + + /// + /// When encounters an invalid option, it stores + /// the value of that option in optopt which can be retrieved + /// with this method. There is no corresponding set method because + /// setting this variable has no effect. + /// + public int Optopt + { + get { return this.optopt; } + } + + /// + /// Returns the index into the array of long options (NOT argv) + /// representing the long option that was found. + /// + public int Longind + { + get { return this.longind; } + } + + /// + /// Exchange the shorter segment with the far end of the longer + /// segment. That puts the shorter segment into the right place. It + /// leaves the longer segment in the right place overall, but it + /// consists of two parts that need to be swapped next. This method is + /// used by for argument permutation. + /// + private void exchange(string[] argv) + { + int bottom = this.firstNonopt; + int middle = this.lastNonopt; + int top = this.optind; + string tem; + + while (top > middle && middle > bottom) + { + if (top - middle > middle - bottom) + { + // Bottom segment is the short one. + int len = middle - bottom; + int i; + + // Swap it with the top part of the top segment. + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + } + // Exclude the moved bottom segment from further swapping. + top -= len; + } + else + { + // Top segment is the short one. + int len = top - middle; + int i; + + // Swap it with the bottom part of the bottom segment. + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + } + // Exclude the moved top segment from further swapping. + bottom += len; + } + } + + // Update records for the slots the non-options now occupy. + + this.firstNonopt += (this.optind - this.lastNonopt); + this.lastNonopt = this.optind; + } + + /// + /// Check to see if an option is a valid long option. Called by + /// . Put in a separate method because this needs + /// to be done twice. (The C getopt authors just copy-pasted the + /// code!). + /// + /// + /// Various things depending on circumstances + /// + private int checkLongOption() + { + LongOpt pfound = null; + int nameend; + bool ambig; + bool exact; + + this.longoptHandled = true; + ambig = false; + exact = false; + this.longind = - 1; + + nameend = this.nextchar.IndexOf("="); + if (nameend == - 1) + nameend = this.nextchar.Length; + + // Test all long options for either exact match or abbreviated + // matches + for (int i = 0; i < this.longOptions.Length; i++) + { + if (this.longOptions[i].Name.StartsWith( + this.nextchar.Substring(0, nameend))) + { + if (this.longOptions[i].Name.Equals( + this.nextchar.Substring(0, nameend))) + { + // Exact match found + pfound = this.longOptions[i]; + this.longind = i; + exact = true; + break; + } + else if (pfound == null) + { + // First nonexact match found + pfound = this.longOptions[i]; + this.longind = i; + } + else + { + // Second or later nonexact match found + ambig = true; + } + } + } // for + + // Print out an error if the option specified was ambiguous + if (ambig && !exact) + { + if (this.opterr) + { + object[] msgArgs = new object[]{ + this.progname, this.argv[optind] }; + System.Console.Error.WriteLine( + this.resManager.GetString("getopt.ambigious", + this.cultureInfo), msgArgs); + } + + this.nextchar = ""; + this.optopt = 0; + ++this.optind; + + return '?'; + } + + if (pfound != null) + { + ++this.optind; + + if (nameend != this.nextchar.Length) + { + if (pfound.HasArg != Argument.No) + { + if (this.nextchar.Substring(nameend).Length > 1) + this.optarg = this.nextchar.Substring(nameend + 1); + else + this.optarg = ""; + } + else + { + if (this.opterr) + { + // -- option + if (argv[this.optind - 1].StartsWith("--")) + { + object[] msgArgs = new object[]{ + this.progname, pfound.Name }; + System.Console.Error.WriteLine( + this.resManager.GetString( + "getopt.arguments1", this.cultureInfo), + msgArgs); + } + // +option or -option + else + { + object[] msgArgs = new object[]{ this.progname, + this.argv[optind - 1][0], pfound.Name}; + System.Console.Error.WriteLine( + this.resManager.GetString( + "getopt.arguments2", this.cultureInfo), + msgArgs); + } + } + + this.nextchar = ""; + this.optopt = pfound.Val; + + return '?'; + } + } // if (nameend) + else if (pfound.HasArg == Argument.Required) + { + if (this.optind < this.argv.Length) + { + this.optarg = this.argv[this.optind]; + ++this.optind; + } + else + { + if (this.opterr) + { + object[] msgArgs = new object[]{ + this.progname, this.argv[this.optind - 1]}; + System.Console.Error.WriteLine( + this.resManager.GetString("getopt.requires", + this.cultureInfo), msgArgs); + } + + this.nextchar = ""; + this.optopt = pfound.Val; + if (this.optstring[0] == ':') + return ':'; + else + return '?'; + } + } // else if (pfound) + + this.nextchar = ""; + + if (pfound.Flag != null) + { + pfound.Flag.Length = 0; + pfound.Flag.Append(pfound.Val); + + return 0; + } + + return pfound.Val; + } // if (pfound != null) + + this.longoptHandled = false; + + return 0; + } + + /// + /// This method returns a char that is the current option that has been + /// parsed from the command line. If the option takes an argument, then + /// the internal variable optarg is set which is a string + /// representing the the value of the argument. This value can be + /// retrieved by the caller using the property. If + /// an invalid option is found, an error message is printed and a + /// '?' is returned. + /// The name of the invalid option character can be retrieved by + /// calling the Optopt property. When there are no more options + /// to be scanned, this method returns -1. The index of first + /// non-option element in argv can be retrieved with the + /// property. + /// + /// + /// Various things as described above. + /// + public int getopt() // not capitalized because of an compiler error + { + this.optarg = null; + + if (this.endparse == true) + return -1; + + if ((this.nextchar == null) || (this.nextchar.Length == 0)) + { + // If we have just processed some options following some + // non-options, exchange them so that the options come first. + if (this.lastNonopt > this.optind) + this.lastNonopt = this.optind; + if (this.firstNonopt > this.optind) + this.firstNonopt = this.optind; + + if (this.ordering == Order.Permute) + { + // If we have just processed some options following some + // non-options, exchange them so that the options come + // first. + if ((this.firstNonopt != this.lastNonopt) && + (this.lastNonopt != this.optind)) + this.exchange(this.argv); + else if (this.lastNonopt != this.optind) + this.firstNonopt = this.optind; + + // Skip any additional non-options + // and extend the range of non-options previously skipped. + while ((this.optind < this.argv.Length) && + ((this.argv[optind].Length == 0) || + (this.argv[this.optind][0] != '-') || + this.argv[optind].Equals("-"))) + this.optind++; + + this.lastNonopt = this.optind; + } + + // The special ARGV-element "--" means premature end of + // options. Skip it like a null option, then exchange with + // previous non-options as if it were an option, then skip + // everything else like a non-option. + if ((this.optind != this.argv.Length) && + this.argv[this.optind].Equals("--")) + { + this.optind++; + + if ((this.firstNonopt != this.lastNonopt) && + (this.lastNonopt != this.optind)) + this.exchange(this.argv); + else if (this.firstNonopt == this.lastNonopt) + this.firstNonopt = this.optind; + + this.lastNonopt = this.argv.Length; + + this.optind = this.argv.Length; + } + + // If we have done all the ARGV-elements, stop the scan + // and back over any non-options that we skipped and permuted. + if (this.optind == this.argv.Length) + { + // Set the next-arg-index to point at the non-options that + // we previously skipped, so the caller will digest them. + if (this.firstNonopt != this.lastNonopt) + this.optind = this.firstNonopt; + + return -1; + } + + // If we have come to a non-option and did not permute it, + // either stop the scan or describe it to the caller and pass + // it by. + if ((this.argv[this.optind].Length == 0) || + (this.argv[this.optind][0] != '-') || + this.argv[this.optind].Equals("-")) + { + if (this.ordering == Order.RequireOrder) + return -1; + + this.optarg = this.argv[optind++]; + return 1; + } + + // We have found another option-ARGV-element. + // Skip the initial punctuation. + if (this.argv[optind].StartsWith("--")) + this.nextchar = this.argv[this.optind].Substring(2); + else + this.nextchar = this.argv[this.optind].Substring(1); + } + + // Decode the current option-ARGV-element. + + /* Check whether the ARGV-element is a long option. + + If longOnly and the ARGV-element has the form "-f", where f is + a valid short option, don't consider it an abbreviated form of + a long option that starts with f. Otherwise there would be no + way to give the -f short option. + + On the other hand, if there's a long option "fubar" and the + ARGV-element is "-fu", do consider that an abbreviation of the + long option, just like "--fu", and not "-f" with arg "u". + + This distinction seems to be the most useful approach. + */ + if ((this.longOptions != null) && + (this.argv[this.optind].StartsWith("--") || (this.longOnly && + ((this.argv[this.optind].Length > 2) || + (this.optstring.IndexOf(this.argv[this.optind][1]) == -1))))) + { + int c = this.checkLongOption(); + + if (this.longoptHandled) + return c; + + // Can't find it as a long option. If this is not + // getopt_long_only, or the option starts with "--" or is not a + // valid short option, then it's an error. Otherwise interpret + // it as a short option. + if (!this.longOnly || this.argv[this.optind].StartsWith("--") + || (this.optstring.IndexOf(this.nextchar[0]) == - 1)) + { + if (this.opterr) + { + if (this.argv[this.optind].StartsWith("--")) + { + object[] msgArgs = new object[]{ + this.progname, this.nextchar }; + System.Console.Error.WriteLine( + this.resManager.GetString("getopt.unrecognized", + this.cultureInfo), msgArgs); + } + else + { + object[] msgArgs = new object[]{ this.progname, + this.argv[optind][0], this.nextchar}; + System.Console.Error.WriteLine( + this.resManager.GetString("getopt.unrecognized2", + this.cultureInfo), msgArgs); + } + } + + this.nextchar = ""; + ++this.optind; + this.optopt = 0; + + return '?'; + } + } // if (longopts) + + // Look at and handle the next short option-character */ + int c2 = this.nextchar[0]; //**** Do we need to check for empty str? + if (this.nextchar.Length > 1) + this.nextchar = this.nextchar.Substring(1); + else + this.nextchar = ""; + + string temp = null; + if (this.optstring.IndexOf((char) c2) != - 1) + temp = this.optstring.Substring( + this.optstring.IndexOf((char) c2)); + + if (this.nextchar.Length == 0) + ++this.optind; + + if ((temp == null) || (c2 == ':')) + { + if (this.opterr) + { + if (this.posixlyCorrect) + { + // 1003.2 specifies the format of this message + object[] msgArgs = new object[]{ + this.progname, (char) c2 }; + System.Console.Error.WriteLine( + this.resManager.GetString("getopt.illegal", + this.cultureInfo), msgArgs); + } + else + { + object[] msgArgs = new object[]{ + this.progname, (char) c2 }; + System.Console.Error.WriteLine( + this.resManager.GetString("getopt.invalid", + this.cultureInfo), msgArgs); + } + } + + this.optopt = c2; + + return '?'; + } + + // Convenience. Treat POSIX -W foo same as long option --foo + if ((temp[0] == 'W') && (temp.Length > 1) && (temp[1] == ';')) + { + if (this.nextchar.Length != 0) + { + this.optarg = this.nextchar; + } + // No further cars in this argv element and no more argv + // elements + else if (this.optind == this.argv.Length) + { + if (this.opterr) + { + // 1003.2 specifies the format of this message. + object[] msgArgs = new object[]{ + this.progname, (char) c2 }; + System.Console.Error.WriteLine( + this.resManager.GetString("getopt.requires2", + this.cultureInfo), msgArgs); + } + + this.optopt = c2; + if (this.optstring[0] == ':') + return ':'; + else + return '?'; + } + else + { + // We already incremented `optind' once; increment it again + // when taking next ARGV-elt as argument. + this.nextchar = this.argv[this.optind]; + this.optarg = this.argv[this.optind]; + } + + c2 = this.checkLongOption(); + + if (this.longoptHandled) + return c2; + // Let the application handle it + else + { + this.nextchar = null; + ++this.optind; + return 'W'; + } + } + + if ((temp.Length > 1) && (temp[1] == ':')) + { + if ((temp.Length > 2) && (temp[2] == ':')) + // This is an option that accepts and argument optionally + { + if (this.nextchar.Length != 0) + { + this.optarg = this.nextchar; + ++this.optind; + } + else + { + this.optarg = null; + } + + this.nextchar = null; + } + else + { + if (this.nextchar.Length != 0) + { + this.optarg = this.nextchar; + ++this.optind; + } + else if (this.optind == this.argv.Length) + { + if (this.opterr) + { + // 1003.2 specifies the format of this message + object[] msgArgs = new object[]{ + this.progname, (char) c2}; + System.Console.Error.WriteLine( + this.resManager.GetString("getopt.requires2", + this.cultureInfo), msgArgs); + } + + this.optopt = c2; + + if (this.optstring[0] == ':') + return ':'; + else + return '?'; + } + else + { + this.optarg = this.argv[this.optind]; + ++this.optind; + + // Ok, here's an obscure Posix case. If we have o:, + // and we get -o -- foo, then we're supposed to skip + // the --, end parsing of options, and make foo an + // operand to -o. Only do this in Posix mode. + if (this.posixlyCorrect && this.optarg.Equals("--")) + { + // If end of argv, error out + if (this.optind == this.argv.Length) + { + if (this.opterr) + { + // 1003.2 specifies the format of this + // message + object[] msgArgs = new object[]{ + this.progname, (char) c2}; + System.Console.Error.WriteLine( + this.resManager.GetString( + "getopt.requires2", this.cultureInfo), + msgArgs); + } + + this.optopt = c2; + + if (this.optstring[0] == ':') + return ':'; + else + return '?'; + } + + // Set new optarg and set to end. Don't permute as + // we do on -- up above since we know we aren't in + // permute mode because of Posix. + this.optarg = this.argv[this.optind]; + ++this.optind; + this.firstNonopt = this.optind; + this.lastNonopt = this.argv.Length; + this.endparse = true; + } + } + + this.nextchar = null; + } + } + + return c2; + } + #endregion + } // Class Getopt +} \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/Gnu.Getopt.csproj b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/Gnu.Getopt.csproj new file mode 100644 index 00000000..4a285aa7 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/Gnu.Getopt.csproj @@ -0,0 +1,122 @@ + + + Local + 9.0.21022 + 2.0 + {379BC478-7D84-4E0E-A4B8-197905C824AE} + Debug + AnyCPU + + + + + Gnu.Getopt + + + JScript + Grid + IE50 + false + Library + Gnu.Getopt + OnBuildSuccess + + + + + 0.0 + + + + + bin\Debug\ + false + 285212672 + false + + + DEBUG;TRACE + bin\Debug\Gnu.Getopt.XML + true + 4096 + false + + + false + false + false + false + 4 + full + prompt + + + bin\Release\ + false + 285212672 + false + + + TRACE + bin\Release\Gnu.Getopt.XML + false + 4096 + false + + + true + false + false + false + 4 + none + prompt + + + + System + + + + + Code + + + Code + + + Code + + + Designer + + + Designer + + + Designer + + + Designer + + + Designer + + + Designer + + + Designer + + + Designer + + + + + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/LongOpt.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/LongOpt.cs new file mode 100644 index 00000000..b961b19c --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/LongOpt.cs @@ -0,0 +1,239 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +/************************************************************************** +/* LongOpt.cs -- C#.NET port of Long option object for Getopt +/* +/* Copyright (c) 1998 by Aaron M. Renn (arenn@urbanophile.com) +/* C#.NET Port Copyright (c) 2004 by Klaus Prückl (klaus.prueckl@aon.at) +/* +/* This program is free software; you can redistribute it and/or modify +/* it under the terms of the GNU Library General Public License as published +/* by the Free Software Foundation; either version 2 of the License or +/* (at your option) any later version. +/* +/* This program is distributed in the hope that it will be useful, but +/* WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU Library General Public License for more details. +/* +/* You should have received a copy of the GNU Library General Public License +/* along with this program; see the file COPYING.LIB. If not, write to +/* the Free Software Foundation Inc., 59 Temple Place - Suite 330, +/* Boston, MA 02111-1307 USA +/**************************************************************************/ + +using System; +using System.Configuration; +using System.Globalization; +using System.Reflection; +using System.Resources; +using System.Text; + +namespace Gnu.Getopt +{ + /// + /// Constant enumeration values used for the LongOpt hasArg + /// constructor argument. + /// + public enum Argument + { + /// + /// This value indicates that the option takes no argument. + /// + No = 0, + /// + /// This value indicates that the option takes an argument that is + /// required. + /// + Required = 1, + /// + /// This value indicates that the option takes an argument that is + /// optional. + /// + Optional = 2 + } + + /// + /// This object represents the definition of a long option in the C# port + /// of GNU getopt. An array of LongOpt objects is passed to the + /// object to define the list of valid long options + /// for a given parsing session. Refer to the + /// documentation for details on the format of long options. + /// + /// Getopt + /// Aaron M. Renn (arenn@urbanophile.com) + /// Klaus Prückl (klaus.prueckl@aon.at) + public class LongOpt + { + #region Instance Variables + /// + /// The name of the long option. + /// + private string name; + + /// + /// Indicates whether the option has no argument, a required argument, + /// or an optional argument. + /// + private Argument hasArg; + + /// + /// If this variable is not null, then the value stored in val + /// is stored here when this long option is encountered. If this is + /// null, the value stored in val is treated as the name of an + /// equivalent short option. + /// + private StringBuilder flag; + + /// + /// The value to store in flag if flag is not null, otherwise + /// the equivalent short option character for this long option. + /// + private int val; + + /// + /// The localized strings are kept in the resources, which can be + /// accessed by the class. + /// + private ResourceManager resManager = new ResourceManager( + "Gnu.Getopt.MessagesBundle", Assembly.GetExecutingAssembly()); + + /// + /// The current UI culture (set to en-US when posixly correctness is + /// enabled). + /// + private CultureInfo cultureInfo = CultureInfo.CurrentUICulture; + #endregion + + #region Constructors + /// + /// Create a new LongOpt object with the given parameter values. If the + /// value passed as is not valid, then an + /// is thrown. + /// + /// + /// The long option string. + /// + /// + /// Indicates whether the option has no argument + /// (), a required argument + /// () or an optional argument + /// (). + /// + /// + /// If non-null, this is a location to store the value of + /// when this option is encountered, otherwise + /// is treated as the equivalent short option + /// character. + /// + /// + /// The value to return for this long option, or the equivalent single + /// letter option to emulate if flag is null. + /// + /// + /// Is thrown if the param is not one of + /// , or + /// . + /// + public LongOpt(string name, Argument hasArg, StringBuilder flag, + int val) + { + // Check for application setting "Gnu.PosixlyCorrect" to determine + // whether to strictly follow the POSIX standard. This replaces the + // "POSIXLY_CORRECT" environment variable in the C version + try + { + if((bool) new AppSettingsReader().GetValue( + "Gnu.PosixlyCorrect", typeof(bool))) + { + this.cultureInfo = new CultureInfo("en-US"); + } + } + catch(Exception) + { + } + + // Validate hasArg + if ((hasArg != Argument.No) && (hasArg != Argument.Required) && + (hasArg != Argument.Optional)) + { + object[] msgArgs = new object[]{hasArg}; + throw new System.ArgumentException(string.Format( + this.resManager.GetString("getopt.invalidValue", + this.cultureInfo), msgArgs)); + } + + // Store off values + this.name = name; + this.hasArg = hasArg; + this.flag = flag; + this.val = val; + } + #endregion + + /// + /// Returns the name of this LongOpt as a string + /// + /// + /// The name of the long option + /// + public string Name + { + get { return this.name; } + } + + /// + /// Returns the value set for the hasArg field for this long + /// option. + /// + /// + /// The value of hasArg. + /// + public Argument HasArg + { + get { return this.hasArg; } + } + + /// + /// Returns the value of the flag field for this long option. + /// + /// + /// The value of flag. + /// + public StringBuilder Flag + { + get { return this.flag; } + } + + /// + /// Returns the value of the val field for this long option. + /// + /// + /// The value of val. + /// + public int Val + { + get { return this.val; } + } + } // Class LongOpt +} \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.cs.resx b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.cs.resx new file mode 100644 index 00000000..fd15ec82 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.cs.resx @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.0.0.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}: volba ''{1}'' je nejednoznaèná + + + {0}: volba ''--{1}'' nepøipou¹tí argument + + + {0}: volba ''{1}{2}'' nepøipou¹tí argument + + + {0}: volba ''{1}'' vy¾aduje argument + + + {0}: nepøípustná volba ''--{1}'' + + + {0}: nepøípustná volba ''{1}{2}'' + + + {0}: nepøípustná volba -- {1} + + + {0}: neplatná volba -- {1} + + + {0}: volba vy¾aduje argument -- {1} + + + Neplatná hodnota {0} parameteru 'has_arg' + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.de.resx b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.de.resx new file mode 100644 index 00000000..df5fe386 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.de.resx @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.0.0.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}: Option ''{1}'' ist zweideutig + + + {0}: Option ''--{1}'' erlaubt kein Argument + + + {0}: Option ''{1}{2}'' erlaubt kein Argument + + + {0}: Option ''{1}'' benötigt ein Argument + + + {0}: Unbekannte Option ''--{1}'' + + + {0}: Unbekannte Option ''{1}{2}'' + + + {0}: Verbotene Option -- {1} + + + {0}: Ungültige Option -- {1} + + + {0}: Option benötigt ein Argument -- {1} + + + Ungültiger Wert {0} für Parameter 'has_arg' + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.fr.resx b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.fr.resx new file mode 100644 index 00000000..4271026b --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.fr.resx @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.0.0.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}: l'option ''{1}'' est ambiguë + + + {0}: l'option ''--{1}'' ne permet pas de paramètre + + + {0}: l'option ''{1}{2}'' ne permet pas de paramètre + + + {0}: l'option ''{1}'' requiert un paramètre + + + {0}: option non reconnue ''--{1}'' + + + {0}: option non reconnue ''{1}{2}'' + + + {0}: option illégale -- {1} + + + {0}: option invalide -- {1} + + + {0}: cette option requiert un paramètre -- {1} + + + Valeur invalide {0} pour le paramètre 'has_arg' + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.hu.resx b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.hu.resx new file mode 100644 index 00000000..d813d976 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.hu.resx @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.0.0.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}: opció ''{1}'' félreérthetõ + + + {0}: opció ''--{1}'' nem enged meg argumentumot + + + {0}: opció ''{1}{2}'' nem enged meg argumentumot + + + {0}: opció ''{1}'' argumentumot igényel + + + {0}: ismeretlen opció ''--{1}'' + + + {0}: ismeretlen opció ''{1}{2}'' + + + {0}: illegális opció -- {1} + + + {0}: érvénytelen opció -- {1} + + + {0}: az opció argumentumot igényel -- {1} + + + Érvénytelen érték {0} a következõ paraméterhez 'has_arg' + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.ja.resx b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.ja.resx new file mode 100644 index 00000000..85032b7a --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.ja.resx @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.0.0.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}: ''{1}'' \u30aa\u30d7\u30b7\u30e7\u30f3\u306f\u66d6\u6627\u3067\u3059\u3002 + + + {0}: ''--{1}'' \u30aa\u30d7\u30b7\u30e7\u30f3\u306f\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u3082\u3061\u307e\u305b\u3093\u3002 + + + {0}: ''{1}{2}'' \u30aa\u30d7\u30b7\u30e7\u30f3\u306f\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u3082\u3061\u307e\u305b\u3093\u3002 + + + {0}: ''{1}'' \u30aa\u30d7\u30b7\u30e7\u30f3\u306b\u306f\u30d1\u30e9\u30e1\u30fc\u30bf\u304c\u5fc5\u8981\u3067\u3059\u3002 + + + {0}: ''--{1}'' \u306f\u7121\u52b9\u306a\u30aa\u30d7\u30b7\u30e7\u30f3\u3067\u3059\u3002 + + + {0}: ''{1}{2}'' \u306f\u7121\u52b9\u306a\u30aa\u30d7\u30b7\u30e7\u30f3\u3067\u3059\u3002 + + + {0}: -- {1} \u306f\u4e0d\u6b63\u306a\u30aa\u30d7\u30b7\u30e7\u30f3\u3067\u3059\u3002 + + + {0}: -- {1} \u30aa\u30d7\u30b7\u30e7\u30f3\u306f\u6b63\u3057\u304f\u3042\u308a\u307e\u305b\u3093\u3002 + + + {0}: -- {1} \u30aa\u30d7\u30b7\u30e7\u30f3\u306b\u306f\u30d1\u30e9\u30e1\u30fc\u30bf\u304c\u5fc5\u8981\u3067\u3059\u3002 + + + {0} \u306f\u3001'has_arg' \u30d1\u30e9\u30e1\u30fc\u30bf\u3068\u3057\u3066\u4e0d\u6b63\u306a\u5024\u3067\u3059\u3002 + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.nl.resx b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.nl.resx new file mode 100644 index 00000000..e22fdc41 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.nl.resx @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.0.0.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}: optie ''{1}'' is ambigue + + + {0}: optie ''--{1}'' staat geen argumenten toe + + + {0}: optie ''{1}{2}'' staat geen argumenten toe + + + {0}: optie ''{1}'' heeft een argument nodig + + + {0}: onbekende optie ''--{1}'' + + + {0}: onbekende optie ''{1}{2}'' + + + {0}: niet-toegestane optie -- {1} + + + {0}: onjuiste optie -- {1} + + + {0}: optie heeft een argument nodig -- {1} + + + Ongeldige waarde {0} voor parameter 'has_arg' + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.no.resx b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.no.resx new file mode 100644 index 00000000..822479d1 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.no.resx @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.0.0.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}: flagget ''{1}'' er flertydig + + + {0}: flagget ''--{1}'' tillater ikke et argument + + + {0}: flagget ''{1}{2}'' tillater ikke et argument + + + {0}: flagget ''{1}'' krever et argument + + + {0}: ukjent flagg ''--{1}'' + + + {0}: ukjent flagg ''{1}{2}'' + + + {0}: ugyldig flagg -- {1} + + + {0}: ugyldig flagg -- {1} + + + {0}: flagget krever et argument -- {1} + + + Ugyldig verdi {0} for parameter 'has_arg' + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.resx b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.resx new file mode 100644 index 00000000..d4ec148a --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Getopt/MessagesBundle.resx @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.0.0.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + {0}: option ''{1}'' is ambiguous + + + {0}: option ''--{1}'' doesn't allow an argument + + + {0}: option ''{1}{2}'' doesn't allow an argument + + + {0}: option ''{1}'' requires an argument + + + {0}: unrecognized option ''--{1}'' + + + {0}: unrecognized option ''{1}{2}'' + + + {0}: invalid option -- {1} + + + {0}: illegal option -- {1} + + + {0}: option requires an argument -- {1} + + + Invalid value {0} for parameter 'has_arg' + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/Gnu.Gettext.csproj b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/Gnu.Gettext.csproj new file mode 100644 index 00000000..e8e1779e --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/Gnu.Gettext.csproj @@ -0,0 +1,61 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {859A653A-7728-4F02-BAF2-A5CD8F991916} + Library + Properties + GNU.Gettext + GNU.Gettext + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/Properties/AssemblyInfo.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..23a9c5b7 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/Properties/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Gettext")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Gettext")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("3be71b7d-867c-46de-bb4d-d12215f0ae67")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/intl.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/intl.cs new file mode 100644 index 00000000..e3408993 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/intl.cs @@ -0,0 +1,520 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +/* GNU gettext for C# + * Copyright (C) 2003 Free Software Foundation, Inc. + * Written by Bruno Haible , 2003. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Library General Public License as published + * by the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, + * USA. + */ + +/* + * Using the GNU gettext approach, compiled message catalogs are assemblies + * containing just one class, a subclass of GettextResourceSet. They are thus + * interoperable with standard ResourceManager based code. + * + * The main differences between the common .NET resources approach and the + * GNU gettext approach are: + * - In the .NET resource approach, the keys are abstract textual shortcuts. + * In the GNU gettext approach, the keys are the English/ASCII version + * of the messages. + * - In the .NET resource approach, the translation files are called + * "Resource.locale.resx" and are UTF-8 encoded XML files. In the GNU gettext + * approach, the translation files are called "Resource.locale.po" and are + * in the encoding the translator has chosen. There are at least three GUI + * translating tools (Emacs PO mode, KDE KBabel, GNOME gtranslator). + * - In the .NET resource approach, the function ResourceManager.GetString + * returns an empty string or throws an InvalidOperationException when no + * translation is found. In the GNU gettext approach, the GetString function + * returns the (English) message key in that case. + * - In the .NET resource approach, there is no support for plural handling. + * In the GNU gettext approach, we have the GetPluralString function. + * + * To compile GNU gettext message catalogs into C# assemblies, the msgfmt + * program can be used. + */ + +using System; /* String, InvalidOperationException, Console */ +using System.Globalization; /* CultureInfo */ +using System.Resources; /* ResourceManager, ResourceSet, IResourceReader */ +using System.Reflection; /* Assembly, ConstructorInfo */ +using System.Collections; /* Hashtable, ICollection, IEnumerator, IDictionaryEnumerator */ +using System.IO; /* Path, FileNotFoundException, Stream */ +using System.Text; /* StringBuilder */ + +namespace GNU.Gettext { + + /// + /// Each instance of this class can be used to lookup translations for a + /// given resource name. For each CultureInfo, it performs the lookup + /// in several assemblies, from most specific over territory-neutral to + /// language-neutral. + /// + public class GettextResourceManager : ResourceManager { + + // ======================== Public Constructors ======================== + + /// + /// Constructor. + /// + /// the resource name, also the assembly base + /// name + public GettextResourceManager (String baseName) + : base (baseName, Assembly.GetCallingAssembly(), typeof (GettextResourceSet)) { + } + + /// + /// Constructor. + /// + /// the resource name, also the assembly base + /// name + public GettextResourceManager (String baseName, Assembly assembly) + : base (baseName, assembly, typeof (GettextResourceSet)) { + } + + // ======================== Implementation ======================== + + /// + /// Loads and returns a satellite assembly. + /// + // This is like Assembly.GetSatelliteAssembly, but uses resourceName + // instead of assembly.GetName().Name, and works around a bug in + // mono-0.28. + private static Assembly GetSatelliteAssembly (Assembly assembly, String resourceName, CultureInfo culture) { + String satelliteExpectedLocation = + Path.GetDirectoryName(assembly.Location) + + Path.DirectorySeparatorChar + culture.Name + + Path.DirectorySeparatorChar + resourceName + ".resources.dll"; + return Assembly.LoadFrom(satelliteExpectedLocation); + } + + /// + /// Loads and returns the satellite assembly for a given culture. + /// + private Assembly MySatelliteAssembly (CultureInfo culture) { + return GetSatelliteAssembly(MainAssembly, BaseName, culture); + } + + /// + /// Converts a resource name to a class name. + /// + /// a nonempty string consisting of alphanumerics and underscores + /// and starting with a letter or underscore + private static String ConstructClassName (String resourceName) { + // We could just return an arbitrary fixed class name, like "Messages", + // assuming that every assembly will only ever contain one + // GettextResourceSet subclass, but this assumption would break the day + // we want to support multi-domain PO files in the same format... + bool valid = (resourceName.Length > 0); + for (int i = 0; valid && i < resourceName.Length; i++) { + char c = resourceName[i]; + if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '_') + || (i > 0 && c >= '0' && c <= '9'))) + valid = false; + } + if (valid) + return resourceName; + else { + // Use hexadecimal escapes, using the underscore as escape character. + String hexdigit = "0123456789abcdef"; + StringBuilder b = new StringBuilder(); + b.Append("__UESCAPED__"); + for (int i = 0; i < resourceName.Length; i++) { + char c = resourceName[i]; + if (c >= 0xd800 && c < 0xdc00 + && i+1 < resourceName.Length + && resourceName[i+1] >= 0xdc00 && resourceName[i+1] < 0xe000) { + // Combine two UTF-16 words to a character. + char c2 = resourceName[i+1]; + int uc = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + b.Append('_'); + b.Append('U'); + b.Append(hexdigit[(uc >> 28) & 0x0f]); + b.Append(hexdigit[(uc >> 24) & 0x0f]); + b.Append(hexdigit[(uc >> 20) & 0x0f]); + b.Append(hexdigit[(uc >> 16) & 0x0f]); + b.Append(hexdigit[(uc >> 12) & 0x0f]); + b.Append(hexdigit[(uc >> 8) & 0x0f]); + b.Append(hexdigit[(uc >> 4) & 0x0f]); + b.Append(hexdigit[uc & 0x0f]); + i++; + } else if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') + || (c >= '0' && c <= '9'))) { + int uc = c; + b.Append('_'); + b.Append('u'); + b.Append(hexdigit[(uc >> 12) & 0x0f]); + b.Append(hexdigit[(uc >> 8) & 0x0f]); + b.Append(hexdigit[(uc >> 4) & 0x0f]); + b.Append(hexdigit[uc & 0x0f]); + } else + b.Append(c); + } + return b.ToString(); + } + } + + /// + /// Instantiates a resource set for a given culture. + /// + /// + /// The expected type name is not valid. + /// + /// + /// satelliteAssembly does not contain the expected type. + /// + /// + /// The type has no no-arguments constructor. + /// + private static GettextResourceSet InstantiateResourceSet (Assembly satelliteAssembly, String resourceName, CultureInfo culture) { + // We expect a class with a culture dependent class name. + Type clazz = satelliteAssembly.GetType(ConstructClassName(resourceName)+"_"+culture.Name.Replace('-','_')); + // We expect it has a no-argument constructor, and invoke it. + ConstructorInfo constructor = clazz.GetConstructor(Type.EmptyTypes); + return constructor.Invoke(null) as GettextResourceSet; + } + + private static GettextResourceSet[] EmptyResourceSetArray = new GettextResourceSet[0]; + + // Cache for already loaded GettextResourceSet cascades. + private Hashtable /* CultureInfo -> GettextResourceSet[] */ Loaded = new Hashtable(); + + /// + /// Returns the array of GettextResourceSets for a given culture, + /// loading them if necessary, and maintaining the cache. + /// + private GettextResourceSet[] GetResourceSetsFor (CultureInfo culture) { + //Console.WriteLine(">> GetResourceSetsFor "+culture); + // Look up in the cache. + GettextResourceSet[] result = Loaded[culture] as GettextResourceSet[]; + if (result == null) { + lock(this) { + // Look up again - maybe another thread has filled in the entry + // while we slept waiting for the lock. + result = Loaded[culture] as GettextResourceSet[]; + if (result == null) { + // Determine the GettextResourceSets for the given culture. + if (culture.Parent == null || culture.Equals(CultureInfo.InvariantCulture)) + // Invariant culture. + result = EmptyResourceSetArray; + else { + // Use a satellite assembly as primary GettextResourceSet, and + // the result for the parent culture as fallback. + GettextResourceSet[] parentResult = GetResourceSetsFor(culture.Parent); + Assembly satelliteAssembly; + try { + satelliteAssembly = MySatelliteAssembly(culture); + } catch (FileNotFoundException e) { + satelliteAssembly = null; + } + if (satelliteAssembly != null) { + GettextResourceSet satelliteResourceSet; + try { + satelliteResourceSet = InstantiateResourceSet(satelliteAssembly, BaseName, culture); + } catch (Exception e) { + Console.Error.WriteLine(e); + Console.Error.WriteLine(e.StackTrace); + satelliteResourceSet = null; + } + if (satelliteResourceSet != null) { + result = new GettextResourceSet[1+parentResult.Length]; + result[0] = satelliteResourceSet; + Array.Copy(parentResult, 0, result, 1, parentResult.Length); + } else + result = parentResult; + } else + result = parentResult; + } + // Put the result into the cache. + Loaded.Add(culture, result); + } + } + } + //Console.WriteLine("<< GetResourceSetsFor "+culture); + return result; + } + + /* + /// + /// Releases all loaded GettextResourceSets and their assemblies. + /// + // TODO: No way to release an Assembly? + public override void ReleaseAllResources () { + ... + } + */ + + /// + /// Returns the translation of in a given culture. + /// + /// the key string to be translated, an ASCII + /// string + /// the translation of , or + /// if none is found + public override String GetString (String msgid, CultureInfo culture) { + foreach (GettextResourceSet rs in GetResourceSetsFor(culture)) { + String translation = rs.GetString(msgid); + if (translation != null) + return translation; + } + // Fallback. + return msgid; + } + + /// + /// Returns the translation of and + /// in a given culture, choosing the right + /// plural form depending on the number . + /// + /// the key string to be translated, an ASCII + /// string + /// the English plural of , + /// an ASCII string + /// the number, should be >= 0 + /// the translation, or or + /// if none is found + public virtual String GetPluralString (String msgid, String msgidPlural, long n, CultureInfo culture) { + foreach (GettextResourceSet rs in GetResourceSetsFor(culture)) { + String translation = rs.GetPluralString(msgid, msgidPlural, n); + if (translation != null) + return translation; + } + // Fallback: Germanic plural form. + return (n == 1 ? msgid : msgidPlural); + } + + // ======================== Public Methods ======================== + + /// + /// Returns the translation of in the current + /// culture. + /// + /// the key string to be translated, an ASCII + /// string + /// the translation of , or + /// if none is found + public override String GetString (String msgid) { + return GetString(msgid, CultureInfo.CurrentUICulture); + } + + /// + /// Returns the translation of and + /// in the current culture, choosing the + /// right plural form depending on the number . + /// + /// the key string to be translated, an ASCII + /// string + /// the English plural of , + /// an ASCII string + /// the number, should be >= 0 + /// the translation, or or + /// if none is found + public virtual String GetPluralString (String msgid, String msgidPlural, long n) { + return GetPluralString(msgid, msgidPlural, n, CultureInfo.CurrentUICulture); + } + + } + + /// + /// + /// Each instance of this class encapsulates a single PO file. + /// + /// + /// This API of this class is not meant to be used directly; use + /// GettextResourceManager instead. + /// + /// + // We need this subclass of ResourceSet, because the plural formula must come + // from the same ResourceSet as the object containing the plural forms. + public class GettextResourceSet : ResourceSet { + + /// + /// Creates a new message catalog. When using this constructor, you + /// must override the ReadResources method, in order to initialize + /// the Table property. The message catalog will support plural + /// forms only if the ReadResources method installs values of type + /// String[] and if the PluralEval method is overridden. + /// + protected GettextResourceSet () + : base (DummyResourceReader) { + } + + /// + /// Creates a new message catalog, by reading the string/value pairs from + /// the given . The message catalog will support + /// plural forms only if the reader can produce values of type + /// String[] and if the PluralEval method is overridden. + /// + public GettextResourceSet (IResourceReader reader) + : base (reader) { + } + + /// + /// Creates a new message catalog, by reading the string/value pairs from + /// the given , which should have the format of + /// a .resources file. The message catalog will not support plural + /// forms. + /// + public GettextResourceSet (Stream stream) + : base (stream) { + } + + /// + /// Creates a new message catalog, by reading the string/value pairs from + /// the file with the given . The file should + /// be in the format of a .resources file. The message catalog will + /// not support plural forms. + /// + public GettextResourceSet (String fileName) + : base (fileName) { + } + + /// + /// Returns the translation of . + /// + /// the key string to be translated, an ASCII + /// string + /// the translation of , or null if + /// none is found + // The default implementation essentially does (String)Table[msgid]. + // Here we also catch the plural form case. + public override String GetString (String msgid) { + Object value = GetObject(msgid); + if (value == null || value is String) + return (String)value; + else if (value is String[]) + // A plural form, but no number is given. + // Like the C implementation, return the first plural form. + return (value as String[])[0]; + else + throw new InvalidOperationException("resource for \""+msgid+"\" in "+GetType().FullName+" is not a string"); + } + + /// + /// Returns the translation of , with possibly + /// case-insensitive lookup. + /// + /// the key string to be translated, an ASCII + /// string + /// the translation of , or null if + /// none is found + // The default implementation essentially does (String)Table[msgid]. + // Here we also catch the plural form case. + public override String GetString (String msgid, bool ignoreCase) { + Object value = GetObject(msgid, ignoreCase); + if (value == null || value is String) + return (String)value; + else if (value is String[]) + // A plural form, but no number is given. + // Like the C implementation, return the first plural form. + return (value as String[])[0]; + else + throw new InvalidOperationException("resource for \""+msgid+"\" in "+GetType().FullName+" is not a string"); + } + + /// + /// Returns the translation of and + /// , choosing the right plural form + /// depending on the number . + /// + /// the key string to be translated, an ASCII + /// string + /// the English plural of , + /// an ASCII string + /// the number, should be >= 0 + /// the translation, or null if none is found + public virtual String GetPluralString (String msgid, String msgidPlural, long n) { + Object value = GetObject(msgid); + if (value == null || value is String) + return (String)value; + else if (value is String[]) { + String[] choices = value as String[]; + long index = PluralEval(n); + return choices[index >= 0 && index < choices.Length ? index : 0]; + } else + throw new InvalidOperationException("resource for \""+msgid+"\" in "+GetType().FullName+" is not a string"); + } + + /// + /// Returns the index of the plural form to be chosen for a given number. + /// The default implementation is the Germanic plural formula: + /// zero for == 1, one for != 1. + /// + protected virtual long PluralEval (long n) { + return (n == 1 ? 0 : 1); + } + + /// + /// Returns the keys of this resource set, i.e. the strings for which + /// GetObject() can return a non-null value. + /// + public virtual ICollection Keys { + get { + return Table.Keys; + } + } + + /// + /// A trivial instance of IResourceReader that does nothing. + /// + // Needed by the no-arguments constructor. + private static IResourceReader DummyResourceReader = new DummyIResourceReader(); + + } + + /// + /// A trivial IResourceReader implementation. + /// + class DummyIResourceReader : IResourceReader { + + // Implementation of IDisposable. + void System.IDisposable.Dispose () { + } + + // Implementation of IEnumerable. + IEnumerator System.Collections.IEnumerable.GetEnumerator () { + return null; + } + + // Implementation of IResourceReader. + void System.Resources.IResourceReader.Close () { + } + IDictionaryEnumerator System.Resources.IResourceReader.GetEnumerator () { + return null; + } + + } + +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/msgfmt.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/msgfmt.cs new file mode 100644 index 00000000..037ccd38 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/msgfmt.cs @@ -0,0 +1,142 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +/* GNU gettext for C# + * Copyright (C) 2003 Free Software Foundation, Inc. + * Written by Bruno Haible , 2003. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* + * This program creates a .resources file from a set of key/value pairs given + * on standard input. + */ + +using System; /* String, Console, Exception */ +using System.IO; /* Stream, BufferedStream, StreamReader */ +using System.Text; /* StringBuilder, UTF8Encoding */ +using System.Resources; /* ResourceWriter */ + +namespace GNU.Gettext { + public class WriteResource { + private StreamReader reader; + // Read a NUL-terminated UTF-8 encoded string. + private String ReadString () { + StringBuilder b = new StringBuilder(); + for (;;) { + int c = reader.Read(); + if (c < 0) // EOF? + return null; + if (c == 0) // End of String? + break; + b.Append((char)c); + } + return b.ToString(); + } + // Read all msgid/msgstr pairs, register them in the ResourceWriter, + // and write the binary contents to the output stream. + private void ReadAllInput (ResourceWriter rw) { + for (;;) { + String msgid = ReadString(); + if (msgid == null) + break; + String msgstr = ReadString(); + if (msgstr == null) + break; + rw.AddResource(msgid, msgstr); + } + rw.Generate(); + } + // Read all msgid/msgstr pairs (each string being NUL-terminated and + // UTF-8 encoded) and write the .resources file to the given filename. + WriteResource (String filename) { + Stream input = new BufferedStream(Console.OpenStandardInput()); + reader = new StreamReader(input, new UTF8Encoding()); + if (filename.Equals("-")) { + BufferedStream output = new BufferedStream(Console.OpenStandardOutput()); + // A temporary output stream is needed because ResourceWriter.Generate + // expects to be able to seek in the Stream. + MemoryStream tmpoutput = new MemoryStream(); + ResourceWriter rw = new ResourceWriter(tmpoutput); + ReadAllInput(rw); +#if __CSCC__ + // Use the ResourceReader to check against pnet-0.6.0 ResourceWriter + // bug. + try { + ResourceReader rr = new ResourceReader(new MemoryStream(tmpoutput.ToArray())); + foreach (System.Collections.DictionaryEntry entry in rr); + } catch (IOException e) { + throw new Exception("class ResourceWriter is buggy", e); + } +#endif + tmpoutput.WriteTo(output); + rw.Close(); + output.Close(); + } else { +#if __CSCC__ + MemoryStream tmpoutput = new MemoryStream(); + ResourceWriter rw = new ResourceWriter(tmpoutput); + ReadAllInput(rw); + // Use the ResourceReader to check against pnet-0.6.0 ResourceWriter + // bug. + try { + ResourceReader rr = new ResourceReader(new MemoryStream(tmpoutput.ToArray())); + foreach (System.Collections.DictionaryEntry entry in rr); + } catch (IOException e) { + throw new Exception("class ResourceWriter is buggy", e); + } + BufferedStream output = new BufferedStream(new FileStream(filename, FileMode.Create, FileAccess.Write)); + tmpoutput.WriteTo(output); + rw.Close(); + output.Close(); +#else + ResourceWriter rw = new ResourceWriter(filename); + ReadAllInput(rw); + rw.Close(); +#endif + } + } + public static int Main (String[] args) { + try { + new WriteResource(args[0]); + } catch (Exception e) { + Console.Error.WriteLine(e); + Console.Error.WriteLine(e.StackTrace); + return 1; + } + return 0; + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/msgunfmt.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/msgunfmt.cs new file mode 100644 index 00000000..d4985881 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Lib/Gnu.Gettext/msgunfmt.cs @@ -0,0 +1,258 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +/* GNU gettext for C# + * Copyright (C) 2003-2004 Free Software Foundation, Inc. + * Written by Bruno Haible , 2003. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* + * This program dumps a GettextResourceSet subclass (in a satellite assembly) + * or a .resources file as a PO file. + */ + +using System; /* Object, String, Type, Console, Exception */ +using System.Reflection; /* Assembly, MethodInfo, ConstructorInfo */ +using System.Collections; /* Hashtable, DictionaryEntry */ +using System.IO; /* BufferedStream, StreamWriter, TextWriter, FileNotFoundException, Path */ +using System.Text; /* StringBuilder, UTF8Encoding */ +using System.Resources; /* ResourceReader */ +using GNU.Gettext; /* GettextResourceSet */ + +namespace GNU.Gettext { + public class DumpResource { + private TextWriter Out; + private void DumpString (String str) { + int n = str.Length; + Out.Write('"'); + for (int i = 0; i < n; i++) { + char c = str[i]; + if (c == 0x0008) { + Out.Write('\\'); Out.Write('b'); + } else if (c == 0x000c) { + Out.Write('\\'); Out.Write('f'); + } else if (c == 0x000a) { + Out.Write('\\'); Out.Write('n'); + } else if (c == 0x000d) { + Out.Write('\\'); Out.Write('r'); + } else if (c == 0x0009) { + Out.Write('\\'); Out.Write('t'); + } else if (c == '\\' || c == '"') { + Out.Write('\\'); Out.Write(c); + } else + Out.Write(c); + } + Out.Write('"'); + } + private void DumpMessage (String msgid, String msgid_plural, Object msgstr) { + Out.Write("msgid "); DumpString(msgid); Out.Write('\n'); + if (msgid_plural != null) { + Out.Write("msgid_plural "); DumpString(msgid_plural); Out.Write('\n'); + for (int i = 0; i < (msgstr as String[]).Length; i++) { + Out.Write("msgstr[" + i + "] "); + DumpString((msgstr as String[])[i]); + Out.Write('\n'); + } + } else { + Out.Write("msgstr "); DumpString(msgstr as String); Out.Write('\n'); + } + Out.Write('\n'); + } + + // ---------------- Dumping a GettextResourceSet ---------------- + + private void Dump (GettextResourceSet catalog) { + MethodInfo pluralMethod = + catalog.GetType().GetMethod("GetMsgidPluralTable", Type.EmptyTypes); + // Search for the header entry. + { + Object header_entry = catalog.GetObject(""); + // If there is no header entry, fake one. + // FIXME: This is not needed; right after po_lex_charset_init set + // the PO charset to UTF-8. + if (header_entry == null) + header_entry = "Content-Type: text/plain; charset=UTF-8\n"; + DumpMessage("", null, header_entry); + } + // Now the other messages. + { + Hashtable plural = null; + if (pluralMethod != null) + plural = pluralMethod.Invoke(catalog, new Object[0]) as Hashtable; + foreach (String key in catalog.Keys) + if (!"".Equals(key)) { + Object value = catalog.GetObject(key); + String key_plural = + (plural != null && value is String[] ? plural[key] as String : null); + DumpMessage(key, key_plural, value); + } + } + } + // Essentially taken from class GettextResourceManager. + private static Assembly GetSatelliteAssembly (String baseDirectory, String resourceName, String cultureName) { + String satelliteExpectedLocation = + baseDirectory + + Path.DirectorySeparatorChar + cultureName + + Path.DirectorySeparatorChar + resourceName + ".resources.dll"; + return Assembly.LoadFrom(satelliteExpectedLocation); + } + // Taken from class GettextResourceManager. + private static String ConstructClassName (String resourceName) { + // We could just return an arbitrary fixed class name, like "Messages", + // assuming that every assembly will only ever contain one + // GettextResourceSet subclass, but this assumption would break the day + // we want to support multi-domain PO files in the same format... + bool valid = (resourceName.Length > 0); + for (int i = 0; valid && i < resourceName.Length; i++) { + char c = resourceName[i]; + if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '_') + || (i > 0 && c >= '0' && c <= '9'))) + valid = false; + } + if (valid) + return resourceName; + else { + // Use hexadecimal escapes, using the underscore as escape character. + String hexdigit = "0123456789abcdef"; + StringBuilder b = new StringBuilder(); + b.Append("__UESCAPED__"); + for (int i = 0; i < resourceName.Length; i++) { + char c = resourceName[i]; + if (c >= 0xd800 && c < 0xdc00 + && i+1 < resourceName.Length + && resourceName[i+1] >= 0xdc00 && resourceName[i+1] < 0xe000) { + // Combine two UTF-16 words to a character. + char c2 = resourceName[i+1]; + int uc = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + b.Append('_'); + b.Append('U'); + b.Append(hexdigit[(uc >> 28) & 0x0f]); + b.Append(hexdigit[(uc >> 24) & 0x0f]); + b.Append(hexdigit[(uc >> 20) & 0x0f]); + b.Append(hexdigit[(uc >> 16) & 0x0f]); + b.Append(hexdigit[(uc >> 12) & 0x0f]); + b.Append(hexdigit[(uc >> 8) & 0x0f]); + b.Append(hexdigit[(uc >> 4) & 0x0f]); + b.Append(hexdigit[uc & 0x0f]); + i++; + } else if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') + || (c >= '0' && c <= '9'))) { + int uc = c; + b.Append('_'); + b.Append('u'); + b.Append(hexdigit[(uc >> 12) & 0x0f]); + b.Append(hexdigit[(uc >> 8) & 0x0f]); + b.Append(hexdigit[(uc >> 4) & 0x0f]); + b.Append(hexdigit[uc & 0x0f]); + } else + b.Append(c); + } + return b.ToString(); + } + } + // Essentially taken from class GettextResourceManager. + private static GettextResourceSet InstantiateResourceSet (Assembly satelliteAssembly, String resourceName, String cultureName) { + Type clazz = satelliteAssembly.GetType(ConstructClassName(resourceName)+"_"+cultureName.Replace('-','_')); + ConstructorInfo constructor = clazz.GetConstructor(Type.EmptyTypes); + return constructor.Invoke(null) as GettextResourceSet; + } + public DumpResource (String baseDirectory, String resourceName, String cultureName) { + // We are only interested in the messages belonging to the locale + // itself, not in the inherited messages. Therefore we instantiate just + // the GettextResourceSet, not a GettextResourceManager. + Assembly satelliteAssembly = + GetSatelliteAssembly(baseDirectory, resourceName, cultureName); + GettextResourceSet catalog = + InstantiateResourceSet(satelliteAssembly, resourceName, cultureName); + BufferedStream stream = new BufferedStream(Console.OpenStandardOutput()); + Out = new StreamWriter(stream, new UTF8Encoding()); + Dump(catalog); + Out.Close(); + stream.Close(); + } + + // ----------------- Dumping a .resources file ------------------ + + public DumpResource (String filename) { + BufferedStream stream = new BufferedStream(Console.OpenStandardOutput()); + Out = new StreamWriter(stream, new UTF8Encoding()); + ResourceReader rr; + if (filename.Equals("-")) { + BufferedStream input = new BufferedStream(Console.OpenStandardInput()); + // A temporary output stream is needed because ResourceReader expects + // to be able to seek in the Stream. + byte[] contents; + { + MemoryStream tmpstream = new MemoryStream(); + byte[] buf = new byte[1024]; + for (;;) { + int n = input.Read(buf, 0, 1024); + if (n == 0) + break; + tmpstream.Write(buf, 0, n); + } + contents = tmpstream.ToArray(); + tmpstream.Close(); + } + MemoryStream tmpinput = new MemoryStream(contents); + rr = new ResourceReader(tmpinput); + } else { + rr = new ResourceReader(filename); + } + foreach (DictionaryEntry entry in rr) // uses rr.GetEnumerator() + DumpMessage(entry.Key as String, null, entry.Value as String); + rr.Close(); + Out.Close(); + stream.Close(); + } + + // -------------------------------------------------------------- + + public static int Main (String[] args) { + try { + if (args.Length > 1) + new DumpResource(args[0], args[1], args[2]); + else + new DumpResource(args[0]); + } catch (Exception e) { + Console.Error.WriteLine(e); + Console.Error.WriteLine(e.StackTrace); + return 1; + } + return 0; + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Gettext.Samples.Console.csproj b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Gettext.Samples.Console.csproj new file mode 100644 index 00000000..79e7a4fe --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Gettext.Samples.Console.csproj @@ -0,0 +1,92 @@ + + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {470FDBA5-04E5-4A9F-80EA-987D1F8D9074} + Exe + Properties + Gettext.Samples.Console + Gettext.Samples.Console + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + True + True + Strings.tt + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + TextTemplatingFileGenerator + Strings.cs + + + + + {D8869765-AB47-4C03-B2C5-E5498A55CA79} + Gettext.Cs + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Program.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Program.cs new file mode 100644 index 00000000..92fbf725 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Program.cs @@ -0,0 +1,76 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; + +namespace Gettext.Samples.Console +{ + class Program + { + static void Main(string[] args) + { + if (SetCultureFromArgs(args)) + { + string translated = Strings.T("Hello world"); + System.Console.Out.WriteLine(translated); + } + } + + private static bool SetCultureFromArgs(string[] args) + { + if (args.Length == 0 || args[0].Contains("?")) + { + PrintUsage(); + return false; + } + else + { + try + { + var culture = CultureInfo.GetCultureInfo(args[0]); + System.Threading.Thread.CurrentThread.CurrentUICulture = culture; + return true; + } + catch (Exception ex) + { + System.Console.Error.WriteLine("Error setting culture from argument {0}:\n{1}", args[0], ex.Message); + return false; + } + } + } + + private static void PrintUsage() + { + System.Console.Out.WriteLine("Use culture short code as only parameter to view message in that language. Choose from one of the available cultures; localized cultures will fall back to neutral ones, and not available ones will fall back to english."); + System.Console.Out.WriteLine(); + System.Console.Out.WriteLine("Available cultures:"); + System.Console.Out.WriteLine(" en"); + System.Console.Out.WriteLine(" es"); + System.Console.Out.WriteLine(" pt"); + System.Console.Out.WriteLine(" fr"); + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Properties/AssemblyInfo.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..a1fdc131 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Properties/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Gettext.Samples.Console")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Gettext.Samples.Console")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b773169f-8efd-4d1c-b873-625eb1f90c26")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/en/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/en/Strings.po new file mode 100644 index 00000000..dec6eeac --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/en/Strings.po @@ -0,0 +1,3 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Console\Program.cs:15 +msgid "Hello world" +msgstr "" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/es/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/es/Strings.po new file mode 100644 index 00000000..8e7edd51 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/es/Strings.po @@ -0,0 +1,3 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Console\Program.cs:15 +msgid "Hello world" +msgstr "Hola mundo" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/fr/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/fr/Strings.po new file mode 100644 index 00000000..ffdf43ca --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/fr/Strings.po @@ -0,0 +1,3 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Console\Program.cs:15 +msgid "Hello world" +msgstr "Bonjour tout le monde" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/pt/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/pt/Strings.po new file mode 100644 index 00000000..0e647052 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Resources/pt/Strings.po @@ -0,0 +1,3 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Console\Program.cs:15 +msgid "Hello world" +msgstr "Olá mundo" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Strings.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Strings.cs new file mode 100644 index 00000000..63569620 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Strings.cs @@ -0,0 +1,168 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + + +// +// This code was generated by a tool. Any changes made manually will be lost +// the next time this code is regenerated. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; +using System.Threading; +using System.Configuration; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +namespace Gettext.Samples.Console +{ + public class Strings + { + private static Object resourceManLock = new Object(); + private static System.Resources.ResourceManager resourceMan; + private static System.Globalization.CultureInfo resourceCulture; + + public const string ResourceName = "Strings"; + + private static string resourcesDir = GetSetting("ResourcesDir", "Resources"); + private static string fileFormat = GetSetting("ResourcesFileFormat", "{{culture}}/{{resource}}.po"); + + private static string GetSetting(string setting, string defaultValue) + { + var section = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings"); + if (section == null) return defaultValue; + else return section[setting] ?? defaultValue; + } + + + /// + /// Resources directory used to retrieve files from. + /// + public static string ResourcesDirectory + { + get { return resourcesDir; } + set { resourcesDir = value; } + } + + /// + /// Format of the file based on culture and resource name. + /// + public static string FileFormat + { + get { return fileFormat; } + set { fileFormat = value; } + } + + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + public static System.Resources.ResourceManager ResourceManager + { + get + { + + if (object.ReferenceEquals(resourceMan, null)) + { + lock (resourceManLock) + { + if (object.ReferenceEquals(resourceMan, null)) + { + var directory = resourcesDir; + var mgr = new global::Gettext.Cs.GettextResourceManager(ResourceName, directory, fileFormat); + resourceMan = mgr; + } + } + } + + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + public static System.Globalization.CultureInfo Culture + { + get { return resourceCulture; } + set { resourceCulture = value; } + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(string t) + { + return T(null, t); + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t) + { + if (String.IsNullOrEmpty(t)) return t; + var translated = ResourceManager.GetString(t, info ?? resourceCulture); + return String.IsNullOrEmpty(translated) ? t : translated; + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(string t, params object[] parameters) + { + return T(null, t, parameters); + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t, params object[] parameters) + { + if (String.IsNullOrEmpty(t)) return t; + return String.Format(T(info, t), parameters); + } + + /// + /// Marks a string for future translation, does not translate it now. + /// + public static string M(string t) + { + return t; + } + + /// + /// Returns the resource set available for the specified culture. + /// + public static System.Resources.ResourceSet GetResourceSet(CultureInfo culture) + { + return ResourceManager.GetResourceSet(culture, true, true); + } + } +} + + diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Strings.tt b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Strings.tt new file mode 100644 index 00000000..fb3c2dc6 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Strings.tt @@ -0,0 +1,9 @@ +<#@ assembly name="System.Configuration" #> + +<# + this.ClassName = "Strings"; + this.ResourceName = "Strings"; + this.NamespaceName = "Gettext.Samples.Console"; + this.DefaultResourceDir = "Resources"; +#> +<#@ include file="..\..\Core\Gettext.Cs\Templates\Strings.tt" #> diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Templates/Strings.pot b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Templates/Strings.pot new file mode 100644 index 00000000..dec6eeac --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/Templates/Strings.pot @@ -0,0 +1,3 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Console\Program.cs:15 +msgid "Hello world" +msgstr "" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/scripts/Extract.bat b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/scripts/Extract.bat new file mode 100644 index 00000000..732363d0 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Console/scripts/Extract.bat @@ -0,0 +1,30 @@ +rem gettext-cs-utils +rem +rem Copyright 2011 Manas Technology Solutions +rem http://www.manas.com.ar/ +rem +rem This library is free software; you can redistribute it and/or +rem modify it under the terms of the GNU Lesser General Public +rem License as published by the Free Software Foundation; either +rem version 2.1 of the License, or (at your option) any later version. +rem +rem This library is distributed in the hope that it will be useful, +rem but WITHOUT ANY WARRANTY; without even the implied warranty of +rem MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +rem Lesser General Public License for more details. +rem +rem You should have received a copy of the GNU Lesser General Public +rem License along with this library. If not, see . + + +@ECHO OFF + +echo. +echo Setting up global variables... +SET path_xgettext=..\..\..\Bin\Gnu.Gettext.Win32\xgettext.exe +SET path_output=..\Templates +SET file_list=.\..\*.cs + +echo. +echo Generating strings po file... +CALL ..\..\..\Scripts\ExtractStrings.bat Strings \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/App.config b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/App.config new file mode 100644 index 00000000..ebb2dc86 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/App.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Gettext.Samples.Database.csproj b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Gettext.Samples.Database.csproj new file mode 100644 index 00000000..37fb0dca --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Gettext.Samples.Database.csproj @@ -0,0 +1,81 @@ + + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {9FBD5BA7-BCE6-48FE-9FB7-396F377D1313} + Exe + Properties + Gettext.Samples.Database + Gettext.Samples.Database + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + Strings.tt + True + True + + + + + {D8869765-AB47-4C03-B2C5-E5498A55CA79} + Gettext.Cs + + + + + + TextTemplatingFileGenerator + Strings.cs + + + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Program.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Program.cs new file mode 100644 index 00000000..27b69fc6 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Program.cs @@ -0,0 +1,77 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; + +namespace Gettext.Samples.Database +{ + class Program + { + static void Main(string[] args) + { + if (SetCultureFromArgs(args)) + { + string translated = Strings.T("Hello world"); + System.Console.Out.WriteLine(translated); + } + } + + private static bool SetCultureFromArgs(string[] args) + { + if (args.Length == 0 || args[0].Contains("?")) + { + PrintUsage(); + return false; + } + else + { + try + { + var culture = CultureInfo.GetCultureInfo(args[0]); + System.Threading.Thread.CurrentThread.CurrentUICulture = culture; + return true; + } + catch (Exception ex) + { + System.Console.Error.WriteLine("Error setting culture from argument {0}:\n{1}", args[0], ex.Message); + return false; + } + } + } + + private static void PrintUsage() + { + System.Console.Out.WriteLine("Use culture short code as only parameter to view message in that language. Choose from one of the available cultures; localized cultures will fall back to neutral ones, and not available ones will fall back to english."); + System.Console.Out.WriteLine(); + System.Console.Out.WriteLine("Available cultures:"); + System.Console.Out.WriteLine(" en"); + System.Console.Out.WriteLine(" es"); + System.Console.Out.WriteLine(" pt"); + System.Console.Out.WriteLine(" fr"); + } + + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Properties/AssemblyInfo.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..df55236f --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Properties/AssemblyInfo.cs @@ -0,0 +1,58 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Gettext.Samples.Database")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Gettext.Samples.Database")] +[assembly: AssemblyCopyright("Copyright © 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4aee2ac6-27d5-4d59-a695-53778e5d56c0")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Strings.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Strings.cs new file mode 100644 index 00000000..80a35301 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Strings.cs @@ -0,0 +1,147 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + + +// +// This code was generated by a tool. Any changes made manually will be lost +// the next time this code is regenerated. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; +using System.Threading; +using System.Configuration; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +namespace Gettext.Samples.Database +{ + public class Strings + { + private static Object resourceManLock = new Object(); + private static System.Resources.ResourceManager resourceMan; + private static System.Globalization.CultureInfo resourceCulture; + + public const string ResourceName = "Strings"; + + + private static string GetSetting(string setting, string defaultValue) + { + var section = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings"); + if (section == null) return defaultValue; + else return section[setting] ?? defaultValue; + } + + + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + public static System.Resources.ResourceManager ResourceManager + { + get + { + + if (object.ReferenceEquals(resourceMan, null)) + { + lock (resourceManLock) + { + if (object.ReferenceEquals(resourceMan, null)) + { + var mgr = new global::Gettext.Cs.DatabaseResourceManager("GettextGetResourceSet"); + resourceMan = mgr; + } + } + } + + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + public static System.Globalization.CultureInfo Culture + { + get { return resourceCulture; } + set { resourceCulture = value; } + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(string t) + { + return T(null, t); + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t) + { + if (String.IsNullOrEmpty(t)) return t; + var translated = ResourceManager.GetString(t, info ?? resourceCulture); + return String.IsNullOrEmpty(translated) ? t : translated; + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(string t, params object[] parameters) + { + return T(null, t, parameters); + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t, params object[] parameters) + { + if (String.IsNullOrEmpty(t)) return t; + return String.Format(T(info, t), parameters); + } + + /// + /// Marks a string for future translation, does not translate it now. + /// + public static string M(string t) + { + return t; + } + + /// + /// Returns the resource set available for the specified culture. + /// + public static System.Resources.ResourceSet GetResourceSet(CultureInfo culture) + { + return ResourceManager.GetResourceSet(culture, true, true); + } + } +} + + diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Strings.tt b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Strings.tt new file mode 100644 index 00000000..cff4cd06 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Strings.tt @@ -0,0 +1,10 @@ +<#@ assembly name="System.Configuration" #> + +<# + this.ClassName = "Strings"; + this.ResourceName = "Strings"; + this.NamespaceName = "Gettext.Samples.Database"; + this.StoredProcedureName = "GettextGetResourceSet"; + this.UseDatabase = true; +#> +<#@ include file="..\..\Core\Gettext.Cs\Templates\Strings.tt" #> diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/en/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/en/Strings.po new file mode 100644 index 00000000..dec6eeac --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/en/Strings.po @@ -0,0 +1,3 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Console\Program.cs:15 +msgid "Hello world" +msgstr "" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/es/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/es/Strings.po new file mode 100644 index 00000000..8e7edd51 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/es/Strings.po @@ -0,0 +1,3 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Console\Program.cs:15 +msgid "Hello world" +msgstr "Hola mundo" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/fr/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/fr/Strings.po new file mode 100644 index 00000000..ffdf43ca --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/fr/Strings.po @@ -0,0 +1,3 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Console\Program.cs:15 +msgid "Hello world" +msgstr "Bonjour tout le monde" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/pt/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/pt/Strings.po new file mode 100644 index 00000000..0e647052 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/Translated/pt/Strings.po @@ -0,0 +1,3 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Console\Program.cs:15 +msgid "Hello world" +msgstr "Olá mundo" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/scripts/DBDump.bat b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/scripts/DBDump.bat new file mode 100644 index 00000000..7cfc8f20 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Database/scripts/DBDump.bat @@ -0,0 +1,39 @@ +rem gettext-cs-utils +rem +rem Copyright 2011 Manas Technology Solutions +rem http://www.manas.com.ar/ +rem +rem This library is free software; you can redistribute it and/or +rem modify it under the terms of the GNU Lesser General Public +rem License as published by the Free Software Foundation; either +rem version 2.1 of the License, or (at your option) any later version. +rem +rem This library is distributed in the hope that it will be useful, +rem but WITHOUT ANY WARRANTY; without even the implied warranty of +rem MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +rem Lesser General Public License for more details. +rem +rem You should have received a copy of the GNU Lesser General Public +rem License along with this library. If not, see . + + +@ECHO OFF + +SET dbrsgen=..\..\..\Tools\Gettext.DatabaseResourceGenerator\bin\Debug\DatabaseResourceGenerator.exe + +echo. +echo Dumping culture sets into DB... + +echo Culture es +CALL %dbrsgen% -i ..\Translated\es\Strings.po -c es -a + +echo Culture en +CALL %dbrsgen% -i ..\Translated\en\Strings.po -c en -a + +echo Culture pt +CALL %dbrsgen% -i ..\Translated\pt\Strings.po -c pt -a + +echo Culture fr +CALL %dbrsgen% -i ..\Translated\fr\Strings.po -c fr -a + +pause \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Content/Site.css b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Content/Site.css new file mode 100644 index 00000000..59aeb2e8 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Content/Site.css @@ -0,0 +1,317 @@ +/*---------------------------------------------------------- +The base color for this template is #5c87b2. If you'd like +to use a different color start by replacing all instances of +#5c87b2 with your new color. +----------------------------------------------------------*/ +body +{ + background-color: #5c87b2; + font-size: .75em; + font-family: Verdana, Helvetica, Sans-Serif; + margin: 0; + padding: 0; + color: #696969; +} + +a:link +{ + color: #034af3; + text-decoration: underline; +} +a:visited +{ + color: #505abc; +} +a:hover +{ + color: #1d60ff; + text-decoration: none; +} +a:active +{ + color: #12eb87; +} + +p, ul +{ + margin-bottom: 20px; + line-height: 1.6em; +} + +/* HEADINGS +----------------------------------------------------------*/ +h1, h2, h3, h4, h5, h6 +{ + font-size: 1.5em; + color: #000; + font-family: Arial, Helvetica, sans-serif; +} + +h1 +{ + font-size: 2em; + padding-bottom: 0; + margin-bottom: 0; +} +h2 +{ + padding: 0 0 10px 0; +} +h3 +{ + font-size: 1.2em; +} +h4 +{ + font-size: 1.1em; +} +h5, h6 +{ + font-size: 1em; +} + +/* this rule styles

tags that are the +first child of the left and right table columns */ +.rightColumn > h1, .rightColumn > h2, .leftColumn > h1, .leftColumn > h2 +{ + margin-top: 0; +} + +/* PRIMARY LAYOUT ELEMENTS +----------------------------------------------------------*/ + +/* you can specify a greater or lesser percentage for the +page width. Or, you can specify an exact pixel width. */ +.page +{ + width: 90%; + margin-left: auto; + margin-right: auto; +} + +#header +{ + position: relative; + margin-bottom: 0px; + color: #000; + padding: 0; +} + +#header h1 +{ + font-weight: bold; + padding: 5px 0; + margin: 0; + color: #fff; + border: none; + line-height: 2em; + font-family: Arial, Helvetica, sans-serif; + font-size: 32px !important; +} + +#main +{ + padding: 30px 30px 15px 30px; + background-color: #fff; + margin-bottom: 30px; + _height: 1px; /* only IE6 applies CSS properties starting with an underscrore */ +} + +#footer +{ + color: #999; + padding: 10px 0; + text-align: center; + line-height: normal; + margin: 0; + font-size: .9em; +} + +/* TAB MENU +----------------------------------------------------------*/ +ul#menu +{ + border-bottom: 1px #5C87B2 solid; + padding: 0 0 2px; + position: relative; + margin: 0; + text-align: right; +} + +ul#menu li +{ + display: inline; + list-style: none; +} + +ul#menu li#greeting +{ + padding: 10px 20px; + font-weight: bold; + text-decoration: none; + line-height: 2.8em; + color: #fff; +} + +ul#menu li a +{ + padding: 10px 20px; + font-weight: bold; + text-decoration: none; + line-height: 2.8em; + background-color: #e8eef4; + color: #034af3; +} + +ul#menu li a:hover +{ + background-color: #fff; + text-decoration: none; +} + +ul#menu li a:active +{ + background-color: #a6e2a6; + text-decoration: none; +} + +ul#menu li.selected a +{ + background-color: #fff; + color: #000; +} + +/* FORM LAYOUT ELEMENTS +----------------------------------------------------------*/ + +fieldset +{ + margin: 1em 0; + padding: 1em; + border: 1px solid #CCC; +} + +fieldset p +{ + margin: 2px 12px 10px 10px; +} + +fieldset label +{ + display: block; +} + +fieldset label.inline +{ + display: inline; +} + +legend +{ + font-size: 1.1em; + font-weight: 600; + padding: 2px 4px 8px 4px; +} + +input[type="text"] +{ + width: 200px; + border: 1px solid #CCC; +} + +input[type="password"] +{ + width: 200px; + border: 1px solid #CCC; +} + +/* TABLE +----------------------------------------------------------*/ + +table +{ + border: solid 1px #e8eef4; + border-collapse: collapse; +} + +table td +{ + padding: 5px; + border: solid 1px #e8eef4; +} + +table th +{ + padding: 6px 5px; + text-align: left; + background-color: #e8eef4; + border: solid 1px #e8eef4; +} + +/* MISC +----------------------------------------------------------*/ +.clear +{ + clear: both; +} + +.error +{ + color:Red; +} + +#menucontainer +{ + margin-top:40px; +} + +div#title +{ + display:block; + float:left; + text-align:left; +} + +#logindisplay +{ + font-size:1.1em; + display:block; + text-align:right; + margin:10px; + color:White; +} + +#logindisplay a:link +{ + color: white; + text-decoration: underline; +} + +#logindisplay a:visited +{ + color: white; + text-decoration: underline; +} + +#logindisplay a:hover +{ + color: white; + text-decoration: none; +} + +.field-validation-error +{ + color: #ff0000; +} + +.input-validation-error +{ + border: 1px solid #ff0000; + background-color: #ffeeee; +} + +.validation-summary-errors +{ + font-weight: bold; + color: #ff0000; +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Controllers/AccountController.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Controllers/AccountController.cs new file mode 100644 index 00000000..0e85fd37 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Controllers/AccountController.cs @@ -0,0 +1,373 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Security.Principal; +using System.Web; +using System.Web.Mvc; +using System.Web.Security; +using System.Web.UI; + +namespace Gettext.Samples.Mvc.Controllers +{ + + [HandleError] + public class AccountController : Controller + { + + // This constructor is used by the MVC framework to instantiate the controller using + // the default forms authentication and membership providers. + + public AccountController() + : this(null, null) + { + } + + // This constructor is not used by the MVC framework but is instead provided for ease + // of unit testing this type. See the comments at the end of this file for more + // information. + public AccountController(IFormsAuthentication formsAuth, IMembershipService service) + { + FormsAuth = formsAuth ?? new FormsAuthenticationService(); + MembershipService = service ?? new AccountMembershipService(); + } + + public IFormsAuthentication FormsAuth + { + get; + private set; + } + + public IMembershipService MembershipService + { + get; + private set; + } + + public ActionResult LogOn() + { + + return View(); + } + + [AcceptVerbs(HttpVerbs.Post)] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", + Justification = "Needs to take same parameter type as Controller.Redirect()")] + public ActionResult LogOn(string userName, string password, bool rememberMe, string returnUrl) + { + + if (!ValidateLogOn(userName, password)) + { + return View(); + } + + FormsAuth.SignIn(userName, rememberMe); + if (!String.IsNullOrEmpty(returnUrl)) + { + return Redirect(returnUrl); + } + else + { + return RedirectToAction("Index", "Home"); + } + } + + public ActionResult LogOff() + { + + FormsAuth.SignOut(); + + return RedirectToAction("Index", "Home"); + } + + public ActionResult Register() + { + + ViewData["PasswordLength"] = MembershipService.MinPasswordLength; + + return View(); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult Register(string userName, string email, string password, string confirmPassword) + { + + ViewData["PasswordLength"] = MembershipService.MinPasswordLength; + + if (ValidateRegistration(userName, email, password, confirmPassword)) + { + // Attempt to register the user + MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email); + + if (createStatus == MembershipCreateStatus.Success) + { + FormsAuth.SignIn(userName, false /* createPersistentCookie */); + return RedirectToAction("Index", "Home"); + } + else + { + ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus)); + } + } + + // If we got this far, something failed, redisplay form + return View(); + } + + [Authorize] + public ActionResult ChangePassword() + { + + ViewData["PasswordLength"] = MembershipService.MinPasswordLength; + + return View(); + } + + [Authorize] + [AcceptVerbs(HttpVerbs.Post)] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", + Justification = "Exceptions result in password not being changed.")] + public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword) + { + + ViewData["PasswordLength"] = MembershipService.MinPasswordLength; + + if (!ValidateChangePassword(currentPassword, newPassword, confirmPassword)) + { + return View(); + } + + try + { + if (MembershipService.ChangePassword(User.Identity.Name, currentPassword, newPassword)) + { + return RedirectToAction("ChangePasswordSuccess"); + } + else + { + ModelState.AddModelError("_FORM", "The current password is incorrect or the new password is invalid."); + return View(); + } + } + catch + { + ModelState.AddModelError("_FORM", "The current password is incorrect or the new password is invalid."); + return View(); + } + } + + public ActionResult ChangePasswordSuccess() + { + + return View(); + } + + protected override void OnActionExecuting(ActionExecutingContext filterContext) + { + if (filterContext.HttpContext.User.Identity is WindowsIdentity) + { + throw new InvalidOperationException("Windows authentication is not supported."); + } + } + + #region Validation Methods + + private bool ValidateChangePassword(string currentPassword, string newPassword, string confirmPassword) + { + if (String.IsNullOrEmpty(currentPassword)) + { + ModelState.AddModelError("currentPassword", "You must specify a current password."); + } + if (newPassword == null || newPassword.Length < MembershipService.MinPasswordLength) + { + ModelState.AddModelError("newPassword", + String.Format(CultureInfo.CurrentCulture, + "You must specify a new password of {0} or more characters.", + MembershipService.MinPasswordLength)); + } + + if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal)) + { + ModelState.AddModelError("_FORM", "The new password and confirmation password do not match."); + } + + return ModelState.IsValid; + } + + private bool ValidateLogOn(string userName, string password) + { + if (String.IsNullOrEmpty(userName)) + { + ModelState.AddModelError("username", "You must specify a username."); + } + if (String.IsNullOrEmpty(password)) + { + ModelState.AddModelError("password", "You must specify a password."); + } + if (!MembershipService.ValidateUser(userName, password)) + { + ModelState.AddModelError("_FORM", "The username or password provided is incorrect."); + } + + return ModelState.IsValid; + } + + private bool ValidateRegistration(string userName, string email, string password, string confirmPassword) + { + if (String.IsNullOrEmpty(userName)) + { + ModelState.AddModelError("username", "You must specify a username."); + } + if (String.IsNullOrEmpty(email)) + { + ModelState.AddModelError("email", "You must specify an email address."); + } + if (password == null || password.Length < MembershipService.MinPasswordLength) + { + ModelState.AddModelError("password", + String.Format(CultureInfo.CurrentCulture, + "You must specify a password of {0} or more characters.", + MembershipService.MinPasswordLength)); + } + if (!String.Equals(password, confirmPassword, StringComparison.Ordinal)) + { + ModelState.AddModelError("_FORM", "The new password and confirmation password do not match."); + } + return ModelState.IsValid; + } + + private static string ErrorCodeToString(MembershipCreateStatus createStatus) + { + // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for + // a full list of status codes. + switch (createStatus) + { + case MembershipCreateStatus.DuplicateUserName: + return "Username already exists. Please enter a different user name."; + + case MembershipCreateStatus.DuplicateEmail: + return "A username for that e-mail address already exists. Please enter a different e-mail address."; + + case MembershipCreateStatus.InvalidPassword: + return "The password provided is invalid. Please enter a valid password value."; + + case MembershipCreateStatus.InvalidEmail: + return "The e-mail address provided is invalid. Please check the value and try again."; + + case MembershipCreateStatus.InvalidAnswer: + return "The password retrieval answer provided is invalid. Please check the value and try again."; + + case MembershipCreateStatus.InvalidQuestion: + return "The password retrieval question provided is invalid. Please check the value and try again."; + + case MembershipCreateStatus.InvalidUserName: + return "The user name provided is invalid. Please check the value and try again."; + + case MembershipCreateStatus.ProviderError: + return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."; + + case MembershipCreateStatus.UserRejected: + return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."; + + default: + return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."; + } + } + #endregion + } + + // The FormsAuthentication type is sealed and contains static members, so it is difficult to + // unit test code that calls its members. The interface and helper class below demonstrate + // how to create an abstract wrapper around such a type in order to make the AccountController + // code unit testable. + + public interface IFormsAuthentication + { + void SignIn(string userName, bool createPersistentCookie); + void SignOut(); + } + + public class FormsAuthenticationService : IFormsAuthentication + { + public void SignIn(string userName, bool createPersistentCookie) + { + FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); + } + public void SignOut() + { + FormsAuthentication.SignOut(); + } + } + + public interface IMembershipService + { + int MinPasswordLength { get; } + + bool ValidateUser(string userName, string password); + MembershipCreateStatus CreateUser(string userName, string password, string email); + bool ChangePassword(string userName, string oldPassword, string newPassword); + } + + public class AccountMembershipService : IMembershipService + { + private MembershipProvider _provider; + + public AccountMembershipService() + : this(null) + { + } + + public AccountMembershipService(MembershipProvider provider) + { + _provider = provider ?? Membership.Provider; + } + + public int MinPasswordLength + { + get + { + return _provider.MinRequiredPasswordLength; + } + } + + public bool ValidateUser(string userName, string password) + { + return _provider.ValidateUser(userName, password); + } + + public MembershipCreateStatus CreateUser(string userName, string password, string email) + { + MembershipCreateStatus status; + _provider.CreateUser(userName, password, email, null, null, true, null, out status); + return status; + } + + public bool ChangePassword(string userName, string oldPassword, string newPassword) + { + MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */); + return currentUser.ChangePassword(oldPassword, newPassword); + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Controllers/HomeController.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Controllers/HomeController.cs new file mode 100644 index 00000000..2428c197 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Controllers/HomeController.cs @@ -0,0 +1,46 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; + +namespace Gettext.Samples.Mvc.Controllers +{ + [HandleError] + public class HomeController : Controller + { + public ActionResult Index() + { + ViewData["Message"] = Strings.T("Welcome to internationalized ASP.NET MVC!"); + + return View(); + } + + public ActionResult About() + { + return View(); + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Default.aspx b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Default.aspx new file mode 100644 index 00000000..62532012 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Default.aspx @@ -0,0 +1,3 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Gettext.Samples.Mvc._Default" %> + +<%-- Please do not delete this file. It is used to ensure that ASP.NET MVC is activated by IIS when a user makes a "/" request to the server. --%> diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Default.aspx.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Default.aspx.cs new file mode 100644 index 00000000..ce36e0bc --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Default.aspx.cs @@ -0,0 +1,44 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System.Web; +using System.Web.Mvc; +using System.Web.UI; + +namespace Gettext.Samples.Mvc +{ + public partial class _Default : Page + { + public void Page_Load(object sender, System.EventArgs e) + { + // Change the current path so that the Routing handler can correctly interpret + // the request, then restore the original path so that the OutputCache module + // can correctly process the response (if caching is enabled). + + string originalPath = Request.Path; + HttpContext.Current.RewritePath(Request.ApplicationPath, false); + IHttpHandler httpHandler = new MvcHttpHandler(); + httpHandler.ProcessRequest(HttpContext.Current); + HttpContext.Current.RewritePath(originalPath, false); + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext.Samples.Mvc.Publish.xml b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext.Samples.Mvc.Publish.xml new file mode 100644 index 00000000..3fd6762b --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext.Samples.Mvc.Publish.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext.Samples.Mvc.csproj b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext.Samples.Mvc.csproj new file mode 100644 index 00000000..152631ee --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext.Samples.Mvc.csproj @@ -0,0 +1,155 @@ + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {208D43F3-84E6-45B9-B6CC-6E3F48E42A82} + {603c0e0b-db56-11dc-be95-000d561079b0};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + Gettext.Samples.Mvc + Gettext.Samples.Mvc + v3.5 + false + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + + + + + + 3.5 + + + 3.5 + + + + 3.5 + + + + + + + + + + + + + + + + + Default.aspx + ASPXCodeBehind + + + Code + + + Strings.tt + True + True + + + Global.asax + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {38474466-DA21-4D19-A4D8-E2E7918480D6} + Gettext.Cs.Web + + + {D8869765-AB47-4C03-B2C5-E5498A55CA79} + Gettext.Cs + + + + + PreserveNewest + + + PreserveNewest + + + TextTemplatingFileGenerator + Strings.cs + + + + + + + + + + + + + + + + + + + + False + True + 6237 + / + + + False + False + + + + + \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/AspTranslateControl.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/AspTranslateControl.cs new file mode 100644 index 00000000..bc437214 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/AspTranslateControl.cs @@ -0,0 +1,44 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Data; +using System.Configuration; +using System.Linq; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.HtmlControls; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Xml.Linq; + +namespace Gettext.Samples.Mvc.Controls +{ + public class t : Gettext.Cs.Web.AspTranslate + { + protected override string Translate(string text) + { + return Strings.T(text); + } + } +} diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Extract.bat b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Extract.bat new file mode 100644 index 00000000..63634a3c --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Extract.bat @@ -0,0 +1,32 @@ +rem gettext-cs-utils +rem +rem Copyright 2011 Manas Technology Solutions +rem http://www.manas.com.ar/ +rem +rem This library is free software; you can redistribute it and/or +rem modify it under the terms of the GNU Lesser General Public +rem License as published by the Free Software Foundation; either +rem version 2.1 of the License, or (at your option) any later version. +rem +rem This library is distributed in the hope that it will be useful, +rem but WITHOUT ANY WARRANTY; without even the implied warranty of +rem MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +rem Lesser General Public License for more details. +rem +rem You should have received a copy of the GNU Lesser General Public +rem License along with this library. If not, see . + + +@ECHO OFF + +echo. +echo Setting up global variables... +SET path_xgettext=..\..\..\Bin\Gnu.Gettext.Win32\xgettext.exe +SET path_aspextract=..\..\..\Tools\Gettext.AspExtract\bin\Debug\AspExtract.exe +SET path_output=.\Templates +SET file_list=..\*.cs +SET asp_files_root=.. + +echo. +echo Generating strings po file... +CALL ..\..\..\Scripts\ExtractAspNetStrings.bat Strings \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Po/en/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Po/en/Strings.po new file mode 100644 index 00000000..13efaae9 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Po/en/Strings.po @@ -0,0 +1,16 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Controllers\HomeController.cs:14 +msgid "Welcome to internationalized ASP.NET MVC!" +msgstr "" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:1 +msgid "Hello world" +msgstr "" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:2 +#, csharp-format +msgid "Go to the {0} page." +msgstr "" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:3 +msgid "home" +msgstr "" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Po/es/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Po/es/Strings.po new file mode 100644 index 00000000..ce7c4d3a --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Po/es/Strings.po @@ -0,0 +1,16 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Controllers\HomeController.cs:14 +msgid "Welcome to internationalized ASP.NET MVC!" +msgstr "Bienvenido a ASP.NET MVC internacionalizado!" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:1 +msgid "Hello world" +msgstr "Hola mundo" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:2 +#, csharp-format +msgid "Go to the {0} page." +msgstr "Ir a la página de {0}." + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:3 +msgid "home" +msgstr "inicio" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Strings.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Strings.cs new file mode 100644 index 00000000..40bbcc34 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Strings.cs @@ -0,0 +1,170 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + + +// +// This code was generated by a tool. Any changes made manually will be lost +// the next time this code is regenerated. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Globalization; +using System.Threading; +using System.Configuration; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +namespace Gettext.Samples.Mvc +{ + public class Strings + { + private static Object resourceManLock = new Object(); + private static System.Resources.ResourceManager resourceMan; + private static System.Globalization.CultureInfo resourceCulture; + + public const string ResourceName = "Strings"; + + private static string resourcesDir = GetSetting("ResourcesDir", "Po"); + private static string fileFormat = GetSetting("ResourcesFileFormat", "{{culture}}/{{resource}}.po"); + + private static string GetSetting(string setting, string defaultValue) + { + var section = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings"); + if (section == null) return defaultValue; + else return section[setting] ?? defaultValue; + } + + + /// + /// Resources directory used to retrieve files from. + /// + public static string ResourcesDirectory + { + get { return resourcesDir; } + set { resourcesDir = value; } + } + + /// + /// Format of the file based on culture and resource name. + /// + public static string FileFormat + { + get { return fileFormat; } + set { fileFormat = value; } + } + + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + public static System.Resources.ResourceManager ResourceManager + { + get + { + + if (object.ReferenceEquals(resourceMan, null)) + { + lock (resourceManLock) + { + if (object.ReferenceEquals(resourceMan, null)) + { + var directory = resourcesDir; + if (System.Web.HttpContext.Current != null) + directory = System.Web.HttpContext.Current.Server.MapPath(directory); + var mgr = new global::Gettext.Cs.GettextResourceManager(ResourceName, directory, fileFormat); + resourceMan = mgr; + } + } + } + + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + public static System.Globalization.CultureInfo Culture + { + get { return resourceCulture; } + set { resourceCulture = value; } + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(string t) + { + return T(null, t); + } + + /// + /// Looks up a localized string; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t) + { + if (String.IsNullOrEmpty(t)) return t; + var translated = ResourceManager.GetString(t, info ?? resourceCulture); + return String.IsNullOrEmpty(translated) ? t : translated; + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(string t, params object[] parameters) + { + return T(null, t, parameters); + } + + /// + /// Looks up a localized string and formats it with the parameters provided; used to mark string for translation as well. + /// + public static string T(CultureInfo info, string t, params object[] parameters) + { + if (String.IsNullOrEmpty(t)) return t; + return String.Format(T(info, t), parameters); + } + + /// + /// Marks a string for future translation, does not translate it now. + /// + public static string M(string t) + { + return t; + } + + /// + /// Returns the resource set available for the specified culture. + /// + public static System.Resources.ResourceSet GetResourceSet(CultureInfo culture) + { + return ResourceManager.GetResourceSet(culture, true, true); + } + } +} + + diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Strings.tt b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Strings.tt new file mode 100644 index 00000000..7fc214f6 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Strings.tt @@ -0,0 +1,9 @@ +<#@ assembly name="System.Configuration" #> + +<# + this.ClassName = "Strings"; + this.ResourceName = "Strings"; + this.NamespaceName = "Gettext.Samples.Mvc"; + this.ServerMapPath = true; +#> +<#@ include file="..\..\..\Core\Gettext.Cs\Templates\Strings.tt" #> diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Templates/Strings.pot b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Templates/Strings.pot new file mode 100644 index 00000000..4ee25a70 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Gettext/Templates/Strings.pot @@ -0,0 +1,16 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Controllers\HomeController.cs:14 +msgid "Welcome to internationalized ASP.NET MVC!" +msgstr "" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:1 +msgid "Hello world" +msgstr "" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:2 +#, csharp-format +msgid "Go to the {0} page." +msgstr "" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:3 +msgid "home" +msgstr "" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Global.asax b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Global.asax new file mode 100644 index 00000000..d41d5e66 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Global.asax @@ -0,0 +1 @@ +<%@ Application Codebehind="Global.asax.cs" Inherits="Gettext.Samples.Mvc.MvcApplication" Language="C#" %> diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Global.asax.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Global.asax.cs new file mode 100644 index 00000000..8865a049 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Global.asax.cs @@ -0,0 +1,54 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; + +namespace Gettext.Samples.Mvc +{ + // Note: For instructions on enabling IIS6 or IIS7 classic mode, + // visit http://go.microsoft.com/?LinkId=9394801 + + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); + + routes.MapRoute( + "Default", // Route name + "{controller}/{action}/{id}", // URL with parameters + new { controller = "Home", action = "Index", id = "" } // Parameter defaults + ); + + } + + protected void Application_Start() + { + RegisterRoutes(RouteTable.Routes); + } + } +} \ No newline at end of file diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Po/en/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Po/en/Strings.po new file mode 100644 index 00000000..4ee25a70 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Po/en/Strings.po @@ -0,0 +1,16 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Controllers\HomeController.cs:14 +msgid "Welcome to internationalized ASP.NET MVC!" +msgstr "" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:1 +msgid "Hello world" +msgstr "" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:2 +#, csharp-format +msgid "Go to the {0} page." +msgstr "" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:3 +msgid "home" +msgstr "" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Po/es/Strings.po b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Po/es/Strings.po new file mode 100644 index 00000000..40c75ac8 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Po/es/Strings.po @@ -0,0 +1,16 @@ +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Controllers\HomeController.cs:14 +msgid "Welcome to internationalized ASP.NET MVC!" +msgstr "Bienvenido a ASP.NET MVC internacionalizado!" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:1 +msgid "Hello world" +msgstr "Hola mundo" + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:2 +#, csharp-format +msgid "Go to the {0} page." +msgstr "Ir a la página de {0}." + +#: E:\Gettext\cs-utils\Gettext.CsUtils\Samples\Gettext.Samples.Mvc\Views\Home\Index.aspx.postrings:3 +msgid "home" +msgstr "inicio" diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Properties/AssemblyInfo.cs b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..350925c2 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Properties/AssemblyInfo.cs @@ -0,0 +1,57 @@ +/** + * gettext-cs-utils + * + * Copyright 2011 Manas Technology Solutions + * http://www.manas.com.ar/ + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + **/ + + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Gettext.Samples.Mvc")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Gettext.Samples.Mvc")] +[assembly: AssemblyCopyright("Copyright © 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f196ad9a-551e-4a6d-8635-413e36224086")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/MicrosoftAjax.debug.js b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/MicrosoftAjax.debug.js new file mode 100644 index 00000000..7b7de621 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/MicrosoftAjax.debug.js @@ -0,0 +1,6850 @@ +// Name: MicrosoftAjax.debug.js +// Assembly: System.Web.Extensions +// Version: 3.5.0.0 +// FileVersion: 3.5.30729.1 +//----------------------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All rights reserved. +//----------------------------------------------------------------------- +// MicrosoftAjax.js +// Microsoft AJAX Framework. + +Function.__typeName = 'Function'; +Function.__class = true; +Function.createCallback = function Function$createCallback(method, context) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "method", type: Function}, + {name: "context", mayBeNull: true} + ]); + if (e) throw e; + return function() { + var l = arguments.length; + if (l > 0) { + var args = []; + for (var i = 0; i < l; i++) { + args[i] = arguments[i]; + } + args[l] = context; + return method.apply(this, args); + } + return method.call(this, context); + } +} +Function.createDelegate = function Function$createDelegate(instance, method) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance", mayBeNull: true}, + {name: "method", type: Function} + ]); + if (e) throw e; + return function() { + return method.apply(instance, arguments); + } +} +Function.emptyFunction = Function.emptyMethod = function Function$emptyMethod() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} +Function._validateParams = function Function$_validateParams(params, expectedParams) { + var e; + e = Function._validateParameterCount(params, expectedParams); + if (e) { + e.popStackFrame(); + return e; + } + for (var i=0; i < params.length; i++) { + var expectedParam = expectedParams[Math.min(i, expectedParams.length - 1)]; + var paramName = expectedParam.name; + if (expectedParam.parameterArray) { + paramName += "[" + (i - expectedParams.length + 1) + "]"; + } + e = Function._validateParameter(params[i], expectedParam, paramName); + if (e) { + e.popStackFrame(); + return e; + } + } + return null; +} +Function._validateParameterCount = function Function$_validateParameterCount(params, expectedParams) { + var maxParams = expectedParams.length; + var minParams = 0; + for (var i=0; i < expectedParams.length; i++) { + if (expectedParams[i].parameterArray) { + maxParams = Number.MAX_VALUE; + } + else if (!expectedParams[i].optional) { + minParams++; + } + } + if (params.length < minParams || params.length > maxParams) { + var e = Error.parameterCount(); + e.popStackFrame(); + return e; + } + return null; +} +Function._validateParameter = function Function$_validateParameter(param, expectedParam, paramName) { + var e; + var expectedType = expectedParam.type; + var expectedInteger = !!expectedParam.integer; + var expectedDomElement = !!expectedParam.domElement; + var mayBeNull = !!expectedParam.mayBeNull; + e = Function._validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName); + if (e) { + e.popStackFrame(); + return e; + } + var expectedElementType = expectedParam.elementType; + var elementMayBeNull = !!expectedParam.elementMayBeNull; + if (expectedType === Array && typeof(param) !== "undefined" && param !== null && + (expectedElementType || !elementMayBeNull)) { + var expectedElementInteger = !!expectedParam.elementInteger; + var expectedElementDomElement = !!expectedParam.elementDomElement; + for (var i=0; i < param.length; i++) { + var elem = param[i]; + e = Function._validateParameterType(elem, expectedElementType, + expectedElementInteger, expectedElementDomElement, elementMayBeNull, + paramName + "[" + i + "]"); + if (e) { + e.popStackFrame(); + return e; + } + } + } + return null; +} +Function._validateParameterType = function Function$_validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName) { + var e; + if (typeof(param) === "undefined") { + if (mayBeNull) { + return null; + } + else { + e = Error.argumentUndefined(paramName); + e.popStackFrame(); + return e; + } + } + if (param === null) { + if (mayBeNull) { + return null; + } + else { + e = Error.argumentNull(paramName); + e.popStackFrame(); + return e; + } + } + if (expectedType && expectedType.__enum) { + if (typeof(param) !== 'number') { + e = Error.argumentType(paramName, Object.getType(param), expectedType); + e.popStackFrame(); + return e; + } + if ((param % 1) === 0) { + var values = expectedType.prototype; + if (!expectedType.__flags || (param === 0)) { + for (var i in values) { + if (values[i] === param) return null; + } + } + else { + var v = param; + for (var i in values) { + var vali = values[i]; + if (vali === 0) continue; + if ((vali & param) === vali) { + v -= vali; + } + if (v === 0) return null; + } + } + } + e = Error.argumentOutOfRange(paramName, param, String.format(Sys.Res.enumInvalidValue, param, expectedType.getName())); + e.popStackFrame(); + return e; + } + if (expectedDomElement) { + var val; + if (typeof(param.nodeType) !== 'number') { + var doc = param.ownerDocument || param.document || param; + if (doc != param) { + var w = doc.defaultView || doc.parentWindow; + val = (w != param) && !(w.document && param.document && (w.document === param.document)); + } + else { + val = (typeof(doc.body) === 'undefined'); + } + } + else { + val = (param.nodeType === 3); + } + if (val) { + e = Error.argument(paramName, Sys.Res.argumentDomElement); + e.popStackFrame(); + return e; + } + } + if (expectedType && !expectedType.isInstanceOfType(param)) { + e = Error.argumentType(paramName, Object.getType(param), expectedType); + e.popStackFrame(); + return e; + } + if (expectedType === Number && expectedInteger) { + if ((param % 1) !== 0) { + e = Error.argumentOutOfRange(paramName, param, Sys.Res.argumentInteger); + e.popStackFrame(); + return e; + } + } + return null; +} + +Error.__typeName = 'Error'; +Error.__class = true; +Error.create = function Error$create(message, errorInfo) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true}, + {name: "errorInfo", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var e = new Error(message); + e.message = message; + if (errorInfo) { + for (var v in errorInfo) { + e[v] = errorInfo[v]; + } + } + e.popStackFrame(); + return e; +} +Error.argument = function Error$argument(paramName, message) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentException: " + (message ? message : Sys.Res.argument); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { name: "Sys.ArgumentException", paramName: paramName }); + e.popStackFrame(); + return e; +} +Error.argumentNull = function Error$argumentNull(paramName, message) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentNullException: " + (message ? message : Sys.Res.argumentNull); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { name: "Sys.ArgumentNullException", paramName: paramName }); + e.popStackFrame(); + return e; +} +Error.argumentOutOfRange = function Error$argumentOutOfRange(paramName, actualValue, message) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "actualValue", mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentOutOfRangeException: " + (message ? message : Sys.Res.argumentOutOfRange); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + if (typeof(actualValue) !== "undefined" && actualValue !== null) { + displayMessage += "\n" + String.format(Sys.Res.actualValue, actualValue); + } + var e = Error.create(displayMessage, { + name: "Sys.ArgumentOutOfRangeException", + paramName: paramName, + actualValue: actualValue + }); + e.popStackFrame(); + return e; +} +Error.argumentType = function Error$argumentType(paramName, actualType, expectedType, message) { + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "actualType", type: Type, mayBeNull: true, optional: true}, + {name: "expectedType", type: Type, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentTypeException: "; + if (message) { + displayMessage += message; + } + else if (actualType && expectedType) { + displayMessage += + String.format(Sys.Res.argumentTypeWithTypes, actualType.getName(), expectedType.getName()); + } + else { + displayMessage += Sys.Res.argumentType; + } + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { + name: "Sys.ArgumentTypeException", + paramName: paramName, + actualType: actualType, + expectedType: expectedType + }); + e.popStackFrame(); + return e; +} +Error.argumentUndefined = function Error$argumentUndefined(paramName, message) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentUndefinedException: " + (message ? message : Sys.Res.argumentUndefined); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { name: "Sys.ArgumentUndefinedException", paramName: paramName }); + e.popStackFrame(); + return e; +} +Error.format = function Error$format(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.FormatException: " + (message ? message : Sys.Res.format); + var e = Error.create(displayMessage, {name: 'Sys.FormatException'}); + e.popStackFrame(); + return e; +} +Error.invalidOperation = function Error$invalidOperation(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.InvalidOperationException: " + (message ? message : Sys.Res.invalidOperation); + var e = Error.create(displayMessage, {name: 'Sys.InvalidOperationException'}); + e.popStackFrame(); + return e; +} +Error.notImplemented = function Error$notImplemented(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.NotImplementedException: " + (message ? message : Sys.Res.notImplemented); + var e = Error.create(displayMessage, {name: 'Sys.NotImplementedException'}); + e.popStackFrame(); + return e; +} +Error.parameterCount = function Error$parameterCount(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ParameterCountException: " + (message ? message : Sys.Res.parameterCount); + var e = Error.create(displayMessage, {name: 'Sys.ParameterCountException'}); + e.popStackFrame(); + return e; +} +Error.prototype.popStackFrame = function Error$popStackFrame() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (typeof(this.stack) === "undefined" || this.stack === null || + typeof(this.fileName) === "undefined" || this.fileName === null || + typeof(this.lineNumber) === "undefined" || this.lineNumber === null) { + return; + } + var stackFrames = this.stack.split("\n"); + var currentFrame = stackFrames[0]; + var pattern = this.fileName + ":" + this.lineNumber; + while(typeof(currentFrame) !== "undefined" && + currentFrame !== null && + currentFrame.indexOf(pattern) === -1) { + stackFrames.shift(); + currentFrame = stackFrames[0]; + } + var nextFrame = stackFrames[1]; + if (typeof(nextFrame) === "undefined" || nextFrame === null) { + return; + } + var nextFrameParts = nextFrame.match(/@(.*):(\d+)$/); + if (typeof(nextFrameParts) === "undefined" || nextFrameParts === null) { + return; + } + this.fileName = nextFrameParts[1]; + this.lineNumber = parseInt(nextFrameParts[2]); + stackFrames.shift(); + this.stack = stackFrames.join("\n"); +} + +Object.__typeName = 'Object'; +Object.__class = true; +Object.getType = function Object$getType(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"} + ]); + if (e) throw e; + var ctor = instance.constructor; + if (!ctor || (typeof(ctor) !== "function") || !ctor.__typeName || (ctor.__typeName === 'Object')) { + return Object; + } + return ctor; +} +Object.getTypeName = function Object$getTypeName(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"} + ]); + if (e) throw e; + return Object.getType(instance).getName(); +} + +String.__typeName = 'String'; +String.__class = true; +String.prototype.endsWith = function String$endsWith(suffix) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "suffix", type: String} + ]); + if (e) throw e; + return (this.substr(this.length - suffix.length) === suffix); +} +String.prototype.startsWith = function String$startsWith(prefix) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "prefix", type: String} + ]); + if (e) throw e; + return (this.substr(0, prefix.length) === prefix); +} +String.prototype.trim = function String$trim() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this.replace(/^\s+|\s+$/g, ''); +} +String.prototype.trimEnd = function String$trimEnd() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this.replace(/\s+$/, ''); +} +String.prototype.trimStart = function String$trimStart() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this.replace(/^\s+/, ''); +} +String.format = function String$format(format, args) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String}, + {name: "args", mayBeNull: true, parameterArray: true} + ]); + if (e) throw e; + return String._toFormattedString(false, arguments); +} +String.localeFormat = function String$localeFormat(format, args) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String}, + {name: "args", mayBeNull: true, parameterArray: true} + ]); + if (e) throw e; + return String._toFormattedString(true, arguments); +} +String._toFormattedString = function String$_toFormattedString(useLocale, args) { + var result = ''; + var format = args[0]; + for (var i=0;;) { + var open = format.indexOf('{', i); + var close = format.indexOf('}', i); + if ((open < 0) && (close < 0)) { + result += format.slice(i); + break; + } + if ((close > 0) && ((close < open) || (open < 0))) { + if (format.charAt(close + 1) !== '}') { + throw Error.argument('format', Sys.Res.stringFormatBraceMismatch); + } + result += format.slice(i, close + 1); + i = close + 2; + continue; + } + result += format.slice(i, open); + i = open + 1; + if (format.charAt(i) === '{') { + result += '{'; + i++; + continue; + } + if (close < 0) throw Error.argument('format', Sys.Res.stringFormatBraceMismatch); + var brace = format.substring(i, close); + var colonIndex = brace.indexOf(':'); + var argNumber = parseInt((colonIndex < 0)? brace : brace.substring(0, colonIndex), 10) + 1; + if (isNaN(argNumber)) throw Error.argument('format', Sys.Res.stringFormatInvalid); + var argFormat = (colonIndex < 0)? '' : brace.substring(colonIndex + 1); + var arg = args[argNumber]; + if (typeof(arg) === "undefined" || arg === null) { + arg = ''; + } + if (arg.toFormattedString) { + result += arg.toFormattedString(argFormat); + } + else if (useLocale && arg.localeFormat) { + result += arg.localeFormat(argFormat); + } + else if (arg.format) { + result += arg.format(argFormat); + } + else + result += arg.toString(); + i = close + 1; + } + return result; +} + +Boolean.__typeName = 'Boolean'; +Boolean.__class = true; +Boolean.parse = function Boolean$parse(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + var v = value.trim().toLowerCase(); + if (v === 'false') return false; + if (v === 'true') return true; + throw Error.argumentOutOfRange('value', value, Sys.Res.boolTrueOrFalse); +} + +Date.__typeName = 'Date'; +Date.__class = true; +Date._appendPreOrPostMatch = function Date$_appendPreOrPostMatch(preMatch, strBuilder) { + var quoteCount = 0; + var escaped = false; + for (var i = 0, il = preMatch.length; i < il; i++) { + var c = preMatch.charAt(i); + switch (c) { + case '\'': + if (escaped) strBuilder.append("'"); + else quoteCount++; + escaped = false; + break; + case '\\': + if (escaped) strBuilder.append("\\"); + escaped = !escaped; + break; + default: + strBuilder.append(c); + escaped = false; + break; + } + } + return quoteCount; +} +Date._expandFormat = function Date$_expandFormat(dtf, format) { + if (!format) { + format = "F"; + } + if (format.length === 1) { + switch (format) { + case "d": + return dtf.ShortDatePattern; + case "D": + return dtf.LongDatePattern; + case "t": + return dtf.ShortTimePattern; + case "T": + return dtf.LongTimePattern; + case "F": + return dtf.FullDateTimePattern; + case "M": case "m": + return dtf.MonthDayPattern; + case "s": + return dtf.SortableDateTimePattern; + case "Y": case "y": + return dtf.YearMonthPattern; + default: + throw Error.format(Sys.Res.formatInvalidString); + } + } + return format; +} +Date._expandYear = function Date$_expandYear(dtf, year) { + if (year < 100) { + var curr = new Date().getFullYear(); + year += curr - (curr % 100); + if (year > dtf.Calendar.TwoDigitYearMax) { + return year - 100; + } + } + return year; +} +Date._getParseRegExp = function Date$_getParseRegExp(dtf, format) { + if (!dtf._parseRegExp) { + dtf._parseRegExp = {}; + } + else if (dtf._parseRegExp[format]) { + return dtf._parseRegExp[format]; + } + var expFormat = Date._expandFormat(dtf, format); + expFormat = expFormat.replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1"); + var regexp = new Sys.StringBuilder("^"); + var groups = []; + var index = 0; + var quoteCount = 0; + var tokenRegExp = Date._getTokenRegExp(); + var match; + while ((match = tokenRegExp.exec(expFormat)) !== null) { + var preMatch = expFormat.slice(index, match.index); + index = tokenRegExp.lastIndex; + quoteCount += Date._appendPreOrPostMatch(preMatch, regexp); + if ((quoteCount%2) === 1) { + regexp.append(match[0]); + continue; + } + switch (match[0]) { + case 'dddd': case 'ddd': + case 'MMMM': case 'MMM': + regexp.append("(\\D+)"); + break; + case 'tt': case 't': + regexp.append("(\\D*)"); + break; + case 'yyyy': + regexp.append("(\\d{4})"); + break; + case 'fff': + regexp.append("(\\d{3})"); + break; + case 'ff': + regexp.append("(\\d{2})"); + break; + case 'f': + regexp.append("(\\d)"); + break; + case 'dd': case 'd': + case 'MM': case 'M': + case 'yy': case 'y': + case 'HH': case 'H': + case 'hh': case 'h': + case 'mm': case 'm': + case 'ss': case 's': + regexp.append("(\\d\\d?)"); + break; + case 'zzz': + regexp.append("([+-]?\\d\\d?:\\d{2})"); + break; + case 'zz': case 'z': + regexp.append("([+-]?\\d\\d?)"); + break; + } + Array.add(groups, match[0]); + } + Date._appendPreOrPostMatch(expFormat.slice(index), regexp); + regexp.append("$"); + var regexpStr = regexp.toString().replace(/\s+/g, "\\s+"); + var parseRegExp = {'regExp': regexpStr, 'groups': groups}; + dtf._parseRegExp[format] = parseRegExp; + return parseRegExp; +} +Date._getTokenRegExp = function Date$_getTokenRegExp() { + return /dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g; +} +Date.parseLocale = function Date$parseLocale(value, formats) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String}, + {name: "formats", mayBeNull: true, optional: true, parameterArray: true} + ]); + if (e) throw e; + return Date._parse(value, Sys.CultureInfo.CurrentCulture, arguments); +} +Date.parseInvariant = function Date$parseInvariant(value, formats) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String}, + {name: "formats", mayBeNull: true, optional: true, parameterArray: true} + ]); + if (e) throw e; + return Date._parse(value, Sys.CultureInfo.InvariantCulture, arguments); +} +Date._parse = function Date$_parse(value, cultureInfo, args) { + var custom = false; + for (var i = 1, il = args.length; i < il; i++) { + var format = args[i]; + if (format) { + custom = true; + var date = Date._parseExact(value, format, cultureInfo); + if (date) return date; + } + } + if (! custom) { + var formats = cultureInfo._getDateTimeFormats(); + for (var i = 0, il = formats.length; i < il; i++) { + var date = Date._parseExact(value, formats[i], cultureInfo); + if (date) return date; + } + } + return null; +} +Date._parseExact = function Date$_parseExact(value, format, cultureInfo) { + value = value.trim(); + var dtf = cultureInfo.dateTimeFormat; + var parseInfo = Date._getParseRegExp(dtf, format); + var match = new RegExp(parseInfo.regExp).exec(value); + if (match === null) return null; + + var groups = parseInfo.groups; + var year = null, month = null, date = null, weekDay = null; + var hour = 0, min = 0, sec = 0, msec = 0, tzMinOffset = null; + var pmHour = false; + for (var j = 0, jl = groups.length; j < jl; j++) { + var matchGroup = match[j+1]; + if (matchGroup) { + switch (groups[j]) { + case 'dd': case 'd': + date = parseInt(matchGroup, 10); + if ((date < 1) || (date > 31)) return null; + break; + case 'MMMM': + month = cultureInfo._getMonthIndex(matchGroup); + if ((month < 0) || (month > 11)) return null; + break; + case 'MMM': + month = cultureInfo._getAbbrMonthIndex(matchGroup); + if ((month < 0) || (month > 11)) return null; + break; + case 'M': case 'MM': + var month = parseInt(matchGroup, 10) - 1; + if ((month < 0) || (month > 11)) return null; + break; + case 'y': case 'yy': + year = Date._expandYear(dtf,parseInt(matchGroup, 10)); + if ((year < 0) || (year > 9999)) return null; + break; + case 'yyyy': + year = parseInt(matchGroup, 10); + if ((year < 0) || (year > 9999)) return null; + break; + case 'h': case 'hh': + hour = parseInt(matchGroup, 10); + if (hour === 12) hour = 0; + if ((hour < 0) || (hour > 11)) return null; + break; + case 'H': case 'HH': + hour = parseInt(matchGroup, 10); + if ((hour < 0) || (hour > 23)) return null; + break; + case 'm': case 'mm': + min = parseInt(matchGroup, 10); + if ((min < 0) || (min > 59)) return null; + break; + case 's': case 'ss': + sec = parseInt(matchGroup, 10); + if ((sec < 0) || (sec > 59)) return null; + break; + case 'tt': case 't': + var upperToken = matchGroup.toUpperCase(); + pmHour = (upperToken === dtf.PMDesignator.toUpperCase()); + if (!pmHour && (upperToken !== dtf.AMDesignator.toUpperCase())) return null; + break; + case 'f': + msec = parseInt(matchGroup, 10) * 100; + if ((msec < 0) || (msec > 999)) return null; + break; + case 'ff': + msec = parseInt(matchGroup, 10) * 10; + if ((msec < 0) || (msec > 999)) return null; + break; + case 'fff': + msec = parseInt(matchGroup, 10); + if ((msec < 0) || (msec > 999)) return null; + break; + case 'dddd': + weekDay = cultureInfo._getDayIndex(matchGroup); + if ((weekDay < 0) || (weekDay > 6)) return null; + break; + case 'ddd': + weekDay = cultureInfo._getAbbrDayIndex(matchGroup); + if ((weekDay < 0) || (weekDay > 6)) return null; + break; + case 'zzz': + var offsets = matchGroup.split(/:/); + if (offsets.length !== 2) return null; + var hourOffset = parseInt(offsets[0], 10); + if ((hourOffset < -12) || (hourOffset > 13)) return null; + var minOffset = parseInt(offsets[1], 10); + if ((minOffset < 0) || (minOffset > 59)) return null; + tzMinOffset = (hourOffset * 60) + (matchGroup.startsWith('-')? -minOffset : minOffset); + break; + case 'z': case 'zz': + var hourOffset = parseInt(matchGroup, 10); + if ((hourOffset < -12) || (hourOffset > 13)) return null; + tzMinOffset = hourOffset * 60; + break; + } + } + } + var result = new Date(); + if (year === null) { + year = result.getFullYear(); + } + if (month === null) { + month = result.getMonth(); + } + if (date === null) { + date = result.getDate(); + } + result.setFullYear(year, month, date); + if (result.getDate() !== date) return null; + if ((weekDay !== null) && (result.getDay() !== weekDay)) { + return null; + } + if (pmHour && (hour < 12)) { + hour += 12; + } + result.setHours(hour, min, sec, msec); + if (tzMinOffset !== null) { + var adjustedMin = result.getMinutes() - (tzMinOffset + result.getTimezoneOffset()); + result.setHours(result.getHours() + parseInt(adjustedMin/60, 10), adjustedMin%60); + } + return result; +} +Date.prototype.format = function Date$format(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.InvariantCulture); +} +Date.prototype.localeFormat = function Date$localeFormat(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.CurrentCulture); +} +Date.prototype._toFormattedString = function Date$_toFormattedString(format, cultureInfo) { + if (!format || (format.length === 0) || (format === 'i')) { + if (cultureInfo && (cultureInfo.name.length > 0)) { + return this.toLocaleString(); + } + else { + return this.toString(); + } + } + var dtf = cultureInfo.dateTimeFormat; + format = Date._expandFormat(dtf, format); + var ret = new Sys.StringBuilder(); + var hour; + function addLeadingZero(num) { + if (num < 10) { + return '0' + num; + } + return num.toString(); + } + function addLeadingZeros(num) { + if (num < 10) { + return '00' + num; + } + if (num < 100) { + return '0' + num; + } + return num.toString(); + } + var quoteCount = 0; + var tokenRegExp = Date._getTokenRegExp(); + for (;;) { + var index = tokenRegExp.lastIndex; + var ar = tokenRegExp.exec(format); + var preMatch = format.slice(index, ar ? ar.index : format.length); + quoteCount += Date._appendPreOrPostMatch(preMatch, ret); + if (!ar) break; + if ((quoteCount%2) === 1) { + ret.append(ar[0]); + continue; + } + switch (ar[0]) { + case "dddd": + ret.append(dtf.DayNames[this.getDay()]); + break; + case "ddd": + ret.append(dtf.AbbreviatedDayNames[this.getDay()]); + break; + case "dd": + ret.append(addLeadingZero(this.getDate())); + break; + case "d": + ret.append(this.getDate()); + break; + case "MMMM": + ret.append(dtf.MonthNames[this.getMonth()]); + break; + case "MMM": + ret.append(dtf.AbbreviatedMonthNames[this.getMonth()]); + break; + case "MM": + ret.append(addLeadingZero(this.getMonth() + 1)); + break; + case "M": + ret.append(this.getMonth() + 1); + break; + case "yyyy": + ret.append(this.getFullYear()); + break; + case "yy": + ret.append(addLeadingZero(this.getFullYear() % 100)); + break; + case "y": + ret.append(this.getFullYear() % 100); + break; + case "hh": + hour = this.getHours() % 12; + if (hour === 0) hour = 12; + ret.append(addLeadingZero(hour)); + break; + case "h": + hour = this.getHours() % 12; + if (hour === 0) hour = 12; + ret.append(hour); + break; + case "HH": + ret.append(addLeadingZero(this.getHours())); + break; + case "H": + ret.append(this.getHours()); + break; + case "mm": + ret.append(addLeadingZero(this.getMinutes())); + break; + case "m": + ret.append(this.getMinutes()); + break; + case "ss": + ret.append(addLeadingZero(this.getSeconds())); + break; + case "s": + ret.append(this.getSeconds()); + break; + case "tt": + ret.append((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator); + break; + case "t": + ret.append(((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator).charAt(0)); + break; + case "f": + ret.append(addLeadingZeros(this.getMilliseconds()).charAt(0)); + break; + case "ff": + ret.append(addLeadingZeros(this.getMilliseconds()).substr(0, 2)); + break; + case "fff": + ret.append(addLeadingZeros(this.getMilliseconds())); + break; + case "z": + hour = this.getTimezoneOffset() / 60; + ret.append(((hour <= 0) ? '+' : '-') + Math.floor(Math.abs(hour))); + break; + case "zz": + hour = this.getTimezoneOffset() / 60; + ret.append(((hour <= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour)))); + break; + case "zzz": + hour = this.getTimezoneOffset() / 60; + ret.append(((hour <= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour))) + + dtf.TimeSeparator + addLeadingZero(Math.abs(this.getTimezoneOffset() % 60))); + break; + } + } + return ret.toString(); +} + +Number.__typeName = 'Number'; +Number.__class = true; +Number.parseLocale = function Number$parseLocale(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + return Number._parse(value, Sys.CultureInfo.CurrentCulture); +} +Number.parseInvariant = function Number$parseInvariant(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + return Number._parse(value, Sys.CultureInfo.InvariantCulture); +} +Number._parse = function Number$_parse(value, cultureInfo) { + value = value.trim(); + + if (value.match(/^[+-]?infinity$/i)) { + return parseFloat(value); + } + if (value.match(/^0x[a-f0-9]+$/i)) { + return parseInt(value); + } + var numFormat = cultureInfo.numberFormat; + var signInfo = Number._parseNumberNegativePattern(value, numFormat, numFormat.NumberNegativePattern); + var sign = signInfo[0]; + var num = signInfo[1]; + + if ((sign === '') && (numFormat.NumberNegativePattern !== 1)) { + signInfo = Number._parseNumberNegativePattern(value, numFormat, 1); + sign = signInfo[0]; + num = signInfo[1]; + } + if (sign === '') sign = '+'; + + var exponent; + var intAndFraction; + var exponentPos = num.indexOf('e'); + if (exponentPos < 0) exponentPos = num.indexOf('E'); + if (exponentPos < 0) { + intAndFraction = num; + exponent = null; + } + else { + intAndFraction = num.substr(0, exponentPos); + exponent = num.substr(exponentPos + 1); + } + + var integer; + var fraction; + var decimalPos = intAndFraction.indexOf(numFormat.NumberDecimalSeparator); + if (decimalPos < 0) { + integer = intAndFraction; + fraction = null; + } + else { + integer = intAndFraction.substr(0, decimalPos); + fraction = intAndFraction.substr(decimalPos + numFormat.NumberDecimalSeparator.length); + } + + integer = integer.split(numFormat.NumberGroupSeparator).join(''); + var altNumGroupSeparator = numFormat.NumberGroupSeparator.replace(/\u00A0/g, " "); + if (numFormat.NumberGroupSeparator !== altNumGroupSeparator) { + integer = integer.split(altNumGroupSeparator).join(''); + } + + var p = sign + integer; + if (fraction !== null) { + p += '.' + fraction; + } + if (exponent !== null) { + var expSignInfo = Number._parseNumberNegativePattern(exponent, numFormat, 1); + if (expSignInfo[0] === '') { + expSignInfo[0] = '+'; + } + p += 'e' + expSignInfo[0] + expSignInfo[1]; + } + if (p.match(/^[+-]?\d*\.?\d*(e[+-]?\d+)?$/)) { + return parseFloat(p); + } + return Number.NaN; +} +Number._parseNumberNegativePattern = function Number$_parseNumberNegativePattern(value, numFormat, numberNegativePattern) { + var neg = numFormat.NegativeSign; + var pos = numFormat.PositiveSign; + switch (numberNegativePattern) { + case 4: + neg = ' ' + neg; + pos = ' ' + pos; + case 3: + if (value.endsWith(neg)) { + return ['-', value.substr(0, value.length - neg.length)]; + } + else if (value.endsWith(pos)) { + return ['+', value.substr(0, value.length - pos.length)]; + } + break; + case 2: + neg += ' '; + pos += ' '; + case 1: + if (value.startsWith(neg)) { + return ['-', value.substr(neg.length)]; + } + else if (value.startsWith(pos)) { + return ['+', value.substr(pos.length)]; + } + break; + case 0: + if (value.startsWith('(') && value.endsWith(')')) { + return ['-', value.substr(1, value.length - 2)]; + } + break; + } + return ['', value]; +} +Number.prototype.format = function Number$format(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.InvariantCulture); +} +Number.prototype.localeFormat = function Number$localeFormat(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.CurrentCulture); +} +Number.prototype._toFormattedString = function Number$_toFormattedString(format, cultureInfo) { + if (!format || (format.length === 0) || (format === 'i')) { + if (cultureInfo && (cultureInfo.name.length > 0)) { + return this.toLocaleString(); + } + else { + return this.toString(); + } + } + + var _percentPositivePattern = ["n %", "n%", "%n" ]; + var _percentNegativePattern = ["-n %", "-n%", "-%n"]; + var _numberNegativePattern = ["(n)","-n","- n","n-","n -"]; + var _currencyPositivePattern = ["$n","n$","$ n","n $"]; + var _currencyNegativePattern = ["($n)","-$n","$-n","$n-","(n$)","-n$","n-$","n$-","-n $","-$ n","n $-","$ n-","$ -n","n- $","($ n)","(n $)"]; + function zeroPad(str, count, left) { + for (var l=str.length; l < count; l++) { + str = (left ? ('0' + str) : (str + '0')); + } + return str; + } + + function expandNumber(number, precision, groupSizes, sep, decimalChar) { + + var curSize = groupSizes[0]; + var curGroupIndex = 1; + var factor = Math.pow(10, precision); + var rounded = (Math.round(number * factor) / factor); + if (!isFinite(rounded)) { + rounded = number; + } + number = rounded; + + var numberString = number.toString(); + var right = ""; + var exponent; + + + var split = numberString.split(/e/i); + numberString = split[0]; + exponent = (split.length > 1 ? parseInt(split[1]) : 0); + split = numberString.split('.'); + numberString = split[0]; + right = split.length > 1 ? split[1] : ""; + + var l; + if (exponent > 0) { + right = zeroPad(right, exponent, false); + numberString += right.slice(0, exponent); + right = right.substr(exponent); + } + else if (exponent < 0) { + exponent = -exponent; + numberString = zeroPad(numberString, exponent+1, true); + right = numberString.slice(-exponent, numberString.length) + right; + numberString = numberString.slice(0, -exponent); + } + if (precision > 0) { + if (right.length > precision) { + right = right.slice(0, precision); + } + else { + right = zeroPad(right, precision, false); + } + right = decimalChar + right; + } + else { + right = ""; + } + var stringIndex = numberString.length-1; + var ret = ""; + while (stringIndex >= 0) { + if (curSize === 0 || curSize > stringIndex) { + if (ret.length > 0) + return numberString.slice(0, stringIndex + 1) + sep + ret + right; + else + return numberString.slice(0, stringIndex + 1) + right; + } + if (ret.length > 0) + ret = numberString.slice(stringIndex - curSize + 1, stringIndex+1) + sep + ret; + else + ret = numberString.slice(stringIndex - curSize + 1, stringIndex+1); + stringIndex -= curSize; + if (curGroupIndex < groupSizes.length) { + curSize = groupSizes[curGroupIndex]; + curGroupIndex++; + } + } + return numberString.slice(0, stringIndex + 1) + sep + ret + right; + } + var nf = cultureInfo.numberFormat; + var number = Math.abs(this); + if (!format) + format = "D"; + var precision = -1; + if (format.length > 1) precision = parseInt(format.slice(1), 10); + var pattern; + switch (format.charAt(0)) { + case "d": + case "D": + pattern = 'n'; + if (precision !== -1) { + number = zeroPad(""+number, precision, true); + } + if (this < 0) number = -number; + break; + case "c": + case "C": + if (this < 0) pattern = _currencyNegativePattern[nf.CurrencyNegativePattern]; + else pattern = _currencyPositivePattern[nf.CurrencyPositivePattern]; + if (precision === -1) precision = nf.CurrencyDecimalDigits; + number = expandNumber(Math.abs(this), precision, nf.CurrencyGroupSizes, nf.CurrencyGroupSeparator, nf.CurrencyDecimalSeparator); + break; + case "n": + case "N": + if (this < 0) pattern = _numberNegativePattern[nf.NumberNegativePattern]; + else pattern = 'n'; + if (precision === -1) precision = nf.NumberDecimalDigits; + number = expandNumber(Math.abs(this), precision, nf.NumberGroupSizes, nf.NumberGroupSeparator, nf.NumberDecimalSeparator); + break; + case "p": + case "P": + if (this < 0) pattern = _percentNegativePattern[nf.PercentNegativePattern]; + else pattern = _percentPositivePattern[nf.PercentPositivePattern]; + if (precision === -1) precision = nf.PercentDecimalDigits; + number = expandNumber(Math.abs(this) * 100, precision, nf.PercentGroupSizes, nf.PercentGroupSeparator, nf.PercentDecimalSeparator); + break; + default: + throw Error.format(Sys.Res.formatBadFormatSpecifier); + } + var regex = /n|\$|-|%/g; + var ret = ""; + for (;;) { + var index = regex.lastIndex; + var ar = regex.exec(pattern); + ret += pattern.slice(index, ar ? ar.index : pattern.length); + if (!ar) + break; + switch (ar[0]) { + case "n": + ret += number; + break; + case "$": + ret += nf.CurrencySymbol; + break; + case "-": + ret += nf.NegativeSign; + break; + case "%": + ret += nf.PercentSymbol; + break; + } + } + return ret; +} + +RegExp.__typeName = 'RegExp'; +RegExp.__class = true; + +Array.__typeName = 'Array'; +Array.__class = true; +Array.add = Array.enqueue = function Array$enqueue(array, item) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + array[array.length] = item; +} +Array.addRange = function Array$addRange(array, items) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "items", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + array.push.apply(array, items); +} +Array.clear = function Array$clear(array) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + array.length = 0; +} +Array.clone = function Array$clone(array) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + if (array.length === 1) { + return [array[0]]; + } + else { + return Array.apply(null, array); + } +} +Array.contains = function Array$contains(array, item) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + return (Array.indexOf(array, item) >= 0); +} +Array.dequeue = function Array$dequeue(array) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + return array.shift(); +} +Array.forEach = function Array$forEach(array, method, instance) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "method", type: Function}, + {name: "instance", mayBeNull: true, optional: true} + ]); + if (e) throw e; + for (var i = 0, l = array.length; i < l; i++) { + var elt = array[i]; + if (typeof(elt) !== 'undefined') method.call(instance, elt, i, array); + } +} +Array.indexOf = function Array$indexOf(array, item, start) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true, optional: true}, + {name: "start", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (typeof(item) === "undefined") return -1; + var length = array.length; + if (length !== 0) { + start = start - 0; + if (isNaN(start)) { + start = 0; + } + else { + if (isFinite(start)) { + start = start - (start % 1); + } + if (start < 0) { + start = Math.max(0, length + start); + } + } + for (var i = start; i < length; i++) { + if ((typeof(array[i]) !== "undefined") && (array[i] === item)) { + return i; + } + } + } + return -1; +} +Array.insert = function Array$insert(array, index, item) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "index", mayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + array.splice(index, 0, item); +} +Array.parse = function Array$parse(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String, mayBeNull: true} + ]); + if (e) throw e; + if (!value) return []; + var v = eval(value); + if (!Array.isInstanceOfType(v)) throw Error.argument('value', Sys.Res.arrayParseBadFormat); + return v; +} +Array.remove = function Array$remove(array, item) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + var index = Array.indexOf(array, item); + if (index >= 0) { + array.splice(index, 1); + } + return (index >= 0); +} +Array.removeAt = function Array$removeAt(array, index) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "index", mayBeNull: true} + ]); + if (e) throw e; + array.splice(index, 1); +} + +if (!window) this.window = this; +window.Type = Function; +Type.__fullyQualifiedIdentifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]([^ \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*[^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\])?$", "i"); +Type.__identifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\][^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*$", "i"); +Type.prototype.callBaseMethod = function Type$callBaseMethod(instance, name, baseArguments) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"}, + {name: "name", type: String}, + {name: "baseArguments", type: Array, mayBeNull: true, optional: true, elementMayBeNull: true} + ]); + if (e) throw e; + var baseMethod = this.getBaseMethod(instance, name); + if (!baseMethod) throw Error.invalidOperation(String.format(Sys.Res.methodNotFound, name)); + if (!baseArguments) { + return baseMethod.apply(instance); + } + else { + return baseMethod.apply(instance, baseArguments); + } +} +Type.prototype.getBaseMethod = function Type$getBaseMethod(instance, name) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"}, + {name: "name", type: String} + ]); + if (e) throw e; + if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this); + var baseType = this.getBaseType(); + if (baseType) { + var baseMethod = baseType.prototype[name]; + return (baseMethod instanceof Function) ? baseMethod : null; + } + return null; +} +Type.prototype.getBaseType = function Type$getBaseType() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return (typeof(this.__baseType) === "undefined") ? null : this.__baseType; +} +Type.prototype.getInterfaces = function Type$getInterfaces() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var result = []; + var type = this; + while(type) { + var interfaces = type.__interfaces; + if (interfaces) { + for (var i = 0, l = interfaces.length; i < l; i++) { + var interfaceType = interfaces[i]; + if (!Array.contains(result, interfaceType)) { + result[result.length] = interfaceType; + } + } + } + type = type.__baseType; + } + return result; +} +Type.prototype.getName = function Type$getName() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return (typeof(this.__typeName) === "undefined") ? "" : this.__typeName; +} +Type.prototype.implementsInterface = function Type$implementsInterface(interfaceType) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "interfaceType", type: Type} + ]); + if (e) throw e; + this.resolveInheritance(); + var interfaceName = interfaceType.getName(); + var cache = this.__interfaceCache; + if (cache) { + var cacheEntry = cache[interfaceName]; + if (typeof(cacheEntry) !== 'undefined') return cacheEntry; + } + else { + cache = this.__interfaceCache = {}; + } + var baseType = this; + while (baseType) { + var interfaces = baseType.__interfaces; + if (interfaces) { + if (Array.indexOf(interfaces, interfaceType) !== -1) { + return cache[interfaceName] = true; + } + } + baseType = baseType.__baseType; + } + return cache[interfaceName] = false; +} +Type.prototype.inheritsFrom = function Type$inheritsFrom(parentType) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "parentType", type: Type} + ]); + if (e) throw e; + this.resolveInheritance(); + var baseType = this.__baseType; + while (baseType) { + if (baseType === parentType) { + return true; + } + baseType = baseType.__baseType; + } + return false; +} +Type.prototype.initializeBase = function Type$initializeBase(instance, baseArguments) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"}, + {name: "baseArguments", type: Array, mayBeNull: true, optional: true, elementMayBeNull: true} + ]); + if (e) throw e; + if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this); + this.resolveInheritance(); + if (this.__baseType) { + if (!baseArguments) { + this.__baseType.apply(instance); + } + else { + this.__baseType.apply(instance, baseArguments); + } + } + return instance; +} +Type.prototype.isImplementedBy = function Type$isImplementedBy(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance", mayBeNull: true} + ]); + if (e) throw e; + if (typeof(instance) === "undefined" || instance === null) return false; + var instanceType = Object.getType(instance); + return !!(instanceType.implementsInterface && instanceType.implementsInterface(this)); +} +Type.prototype.isInstanceOfType = function Type$isInstanceOfType(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance", mayBeNull: true} + ]); + if (e) throw e; + if (typeof(instance) === "undefined" || instance === null) return false; + if (instance instanceof this) return true; + var instanceType = Object.getType(instance); + return !!(instanceType === this) || + (instanceType.inheritsFrom && instanceType.inheritsFrom(this)) || + (instanceType.implementsInterface && instanceType.implementsInterface(this)); +} +Type.prototype.registerClass = function Type$registerClass(typeName, baseType, interfaceTypes) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "typeName", type: String}, + {name: "baseType", type: Type, mayBeNull: true, optional: true}, + {name: "interfaceTypes", type: Type, parameterArray: true} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName); + var parsedName; + try { + parsedName = eval(typeName); + } + catch(e) { + throw Error.argument('typeName', Sys.Res.argumentTypeName); + } + if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); + if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); + if ((arguments.length > 1) && (typeof(baseType) === 'undefined')) throw Error.argumentUndefined('baseType'); + if (baseType && !baseType.__class) throw Error.argument('baseType', Sys.Res.baseNotAClass); + this.prototype.constructor = this; + this.__typeName = typeName; + this.__class = true; + if (baseType) { + this.__baseType = baseType; + this.__basePrototypePending = true; + } + Sys.__upperCaseTypes[typeName.toUpperCase()] = this; + if (interfaceTypes) { + this.__interfaces = []; + this.resolveInheritance(); + for (var i = 2, l = arguments.length; i < l; i++) { + var interfaceType = arguments[i]; + if (!interfaceType.__interface) throw Error.argument('interfaceTypes[' + (i - 2) + ']', Sys.Res.notAnInterface); + for (var methodName in interfaceType.prototype) { + var method = interfaceType.prototype[methodName]; + if (!this.prototype[methodName]) { + this.prototype[methodName] = method; + } + } + this.__interfaces.push(interfaceType); + } + } + Sys.__registeredTypes[typeName] = true; + return this; +} +Type.prototype.registerInterface = function Type$registerInterface(typeName) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "typeName", type: String} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName); + var parsedName; + try { + parsedName = eval(typeName); + } + catch(e) { + throw Error.argument('typeName', Sys.Res.argumentTypeName); + } + if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); + if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); + Sys.__upperCaseTypes[typeName.toUpperCase()] = this; + this.prototype.constructor = this; + this.__typeName = typeName; + this.__interface = true; + Sys.__registeredTypes[typeName] = true; + return this; +} +Type.prototype.resolveInheritance = function Type$resolveInheritance() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this.__basePrototypePending) { + var baseType = this.__baseType; + baseType.resolveInheritance(); + for (var memberName in baseType.prototype) { + var memberValue = baseType.prototype[memberName]; + if (!this.prototype[memberName]) { + this.prototype[memberName] = memberValue; + } + } + delete this.__basePrototypePending; + } +} +Type.getRootNamespaces = function Type$getRootNamespaces() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return Array.clone(Sys.__rootNamespaces); +} +Type.isClass = function Type$isClass(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__class; +} +Type.isInterface = function Type$isInterface(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__interface; +} +Type.isNamespace = function Type$isNamespace(object) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(object) === 'undefined') || (object === null)) return false; + return !!object.__namespace; +} +Type.parse = function Type$parse(typeName, ns) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "typeName", type: String, mayBeNull: true}, + {name: "ns", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var fn; + if (ns) { + fn = Sys.__upperCaseTypes[ns.getName().toUpperCase() + '.' + typeName.toUpperCase()]; + return fn || null; + } + if (!typeName) return null; + if (!Type.__htClasses) { + Type.__htClasses = {}; + } + fn = Type.__htClasses[typeName]; + if (!fn) { + fn = eval(typeName); + if (typeof(fn) !== 'function') throw Error.argument('typeName', Sys.Res.notATypeName); + Type.__htClasses[typeName] = fn; + } + return fn; +} +Type.registerNamespace = function Type$registerNamespace(namespacePath) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "namespacePath", type: String} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(namespacePath)) throw Error.argument('namespacePath', Sys.Res.invalidNameSpace); + var rootObject = window; + var namespaceParts = namespacePath.split('.'); + for (var i = 0; i < namespaceParts.length; i++) { + var currentPart = namespaceParts[i]; + var ns = rootObject[currentPart]; + if (ns && !ns.__namespace) { + throw Error.invalidOperation(String.format(Sys.Res.namespaceContainsObject, namespaceParts.splice(0, i + 1).join('.'))); + } + if (!ns) { + ns = rootObject[currentPart] = { + __namespace: true, + __typeName: namespaceParts.slice(0, i + 1).join('.') + }; + if (i === 0) { + Sys.__rootNamespaces[Sys.__rootNamespaces.length] = ns; + } + var parsedName; + try { + parsedName = eval(ns.__typeName); + } + catch(e) { + parsedName = null; + } + if (parsedName !== ns) { + delete rootObject[currentPart]; + throw Error.argument('namespacePath', Sys.Res.invalidNameSpace); + } + ns.getName = function ns$getName() {return this.__typeName;} + } + rootObject = ns; + } +} +window.Sys = { + __namespace: true, + __typeName: "Sys", + getName: function() {return "Sys";}, + __upperCaseTypes: {} +}; +Sys.__rootNamespaces = [Sys]; +Sys.__registeredTypes = {}; + +Sys.IDisposable = function Sys$IDisposable() { + throw Error.notImplemented(); +} + function Sys$IDisposable$dispose() { + throw Error.notImplemented(); + } +Sys.IDisposable.prototype = { + dispose: Sys$IDisposable$dispose +} +Sys.IDisposable.registerInterface('Sys.IDisposable'); + +Sys.StringBuilder = function Sys$StringBuilder(initialText) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "initialText", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._parts = (typeof(initialText) !== 'undefined' && initialText !== null && initialText !== '') ? + [initialText.toString()] : []; + this._value = {}; + this._len = 0; +} + function Sys$StringBuilder$append(text) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "text", mayBeNull: true} + ]); + if (e) throw e; + this._parts[this._parts.length] = text; + } + function Sys$StringBuilder$appendLine(text) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "text", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._parts[this._parts.length] = + ((typeof(text) === 'undefined') || (text === null) || (text === '')) ? + '\r\n' : text + '\r\n'; + } + function Sys$StringBuilder$clear() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._parts = []; + this._value = {}; + this._len = 0; + } + function Sys$StringBuilder$isEmpty() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._parts.length === 0) return true; + return this.toString() === ''; + } + function Sys$StringBuilder$toString(separator) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "separator", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + separator = separator || ''; + var parts = this._parts; + if (this._len !== parts.length) { + this._value = {}; + this._len = parts.length; + } + var val = this._value; + if (typeof(val[separator]) === 'undefined') { + if (separator !== '') { + for (var i = 0; i < parts.length;) { + if ((typeof(parts[i]) === 'undefined') || (parts[i] === '') || (parts[i] === null)) { + parts.splice(i, 1); + } + else { + i++; + } + } + } + val[separator] = this._parts.join(separator); + } + return val[separator]; + } +Sys.StringBuilder.prototype = { + append: Sys$StringBuilder$append, + appendLine: Sys$StringBuilder$appendLine, + clear: Sys$StringBuilder$clear, + isEmpty: Sys$StringBuilder$isEmpty, + toString: Sys$StringBuilder$toString +} +Sys.StringBuilder.registerClass('Sys.StringBuilder'); + +if (!window.XMLHttpRequest) { + window.XMLHttpRequest = function window$XMLHttpRequest() { + var progIDs = [ 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP' ]; + for (var i = 0, l = progIDs.length; i < l; i++) { + try { + return new ActiveXObject(progIDs[i]); + } + catch (ex) { + } + } + return null; + } +} + +Sys.Browser = {}; +Sys.Browser.InternetExplorer = {}; +Sys.Browser.Firefox = {}; +Sys.Browser.Safari = {}; +Sys.Browser.Opera = {}; +Sys.Browser.agent = null; +Sys.Browser.hasDebuggerStatement = false; +Sys.Browser.name = navigator.appName; +Sys.Browser.version = parseFloat(navigator.appVersion); +Sys.Browser.documentMode = 0; +if (navigator.userAgent.indexOf(' MSIE ') > -1) { + Sys.Browser.agent = Sys.Browser.InternetExplorer; + Sys.Browser.version = parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]); + if (Sys.Browser.version >= 8) { + if (document.documentMode >= 7) { + Sys.Browser.documentMode = document.documentMode; + } + } + Sys.Browser.hasDebuggerStatement = true; +} +else if (navigator.userAgent.indexOf(' Firefox/') > -1) { + Sys.Browser.agent = Sys.Browser.Firefox; + Sys.Browser.version = parseFloat(navigator.userAgent.match(/ Firefox\/(\d+\.\d+)/)[1]); + Sys.Browser.name = 'Firefox'; + Sys.Browser.hasDebuggerStatement = true; +} +else if (navigator.userAgent.indexOf(' AppleWebKit/') > -1) { + Sys.Browser.agent = Sys.Browser.Safari; + Sys.Browser.version = parseFloat(navigator.userAgent.match(/ AppleWebKit\/(\d+(\.\d+)?)/)[1]); + Sys.Browser.name = 'Safari'; +} +else if (navigator.userAgent.indexOf('Opera/') > -1) { + Sys.Browser.agent = Sys.Browser.Opera; +} +Type.registerNamespace('Sys.UI'); + +Sys._Debug = function Sys$_Debug() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} + function Sys$_Debug$_appendConsole(text) { + if ((typeof(Debug) !== 'undefined') && Debug.writeln) { + Debug.writeln(text); + } + if (window.console && window.console.log) { + window.console.log(text); + } + if (window.opera) { + window.opera.postError(text); + } + if (window.debugService) { + window.debugService.trace(text); + } + } + function Sys$_Debug$_appendTrace(text) { + var traceElement = document.getElementById('TraceConsole'); + if (traceElement && (traceElement.tagName.toUpperCase() === 'TEXTAREA')) { + traceElement.value += text + '\n'; + } + } + function Sys$_Debug$assert(condition, message, displayCaller) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "condition", type: Boolean}, + {name: "message", type: String, mayBeNull: true, optional: true}, + {name: "displayCaller", type: Boolean, optional: true} + ]); + if (e) throw e; + if (!condition) { + message = (displayCaller && this.assert.caller) ? + String.format(Sys.Res.assertFailedCaller, message, this.assert.caller) : + String.format(Sys.Res.assertFailed, message); + if (confirm(String.format(Sys.Res.breakIntoDebugger, message))) { + this.fail(message); + } + } + } + function Sys$_Debug$clearTrace() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var traceElement = document.getElementById('TraceConsole'); + if (traceElement && (traceElement.tagName.toUpperCase() === 'TEXTAREA')) { + traceElement.value = ''; + } + } + function Sys$_Debug$fail(message) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true} + ]); + if (e) throw e; + this._appendConsole(message); + if (Sys.Browser.hasDebuggerStatement) { + eval('debugger'); + } + } + function Sys$_Debug$trace(text) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "text"} + ]); + if (e) throw e; + this._appendConsole(text); + this._appendTrace(text); + } + function Sys$_Debug$traceDump(object, name) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", mayBeNull: true}, + {name: "name", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var text = this._traceDump(object, name, true); + } + function Sys$_Debug$_traceDump(object, name, recursive, indentationPadding, loopArray) { + name = name? name : 'traceDump'; + indentationPadding = indentationPadding? indentationPadding : ''; + if (object === null) { + this.trace(indentationPadding + name + ': null'); + return; + } + switch(typeof(object)) { + case 'undefined': + this.trace(indentationPadding + name + ': Undefined'); + break; + case 'number': case 'string': case 'boolean': + this.trace(indentationPadding + name + ': ' + object); + break; + default: + if (Date.isInstanceOfType(object) || RegExp.isInstanceOfType(object)) { + this.trace(indentationPadding + name + ': ' + object.toString()); + break; + } + if (!loopArray) { + loopArray = []; + } + else if (Array.contains(loopArray, object)) { + this.trace(indentationPadding + name + ': ...'); + return; + } + Array.add(loopArray, object); + if ((object == window) || (object === document) || + (window.HTMLElement && (object instanceof HTMLElement)) || + (typeof(object.nodeName) === 'string')) { + var tag = object.tagName? object.tagName : 'DomElement'; + if (object.id) { + tag += ' - ' + object.id; + } + this.trace(indentationPadding + name + ' {' + tag + '}'); + } + else { + var typeName = Object.getTypeName(object); + this.trace(indentationPadding + name + (typeof(typeName) === 'string' ? ' {' + typeName + '}' : '')); + if ((indentationPadding === '') || recursive) { + indentationPadding += " "; + var i, length, properties, p, v; + if (Array.isInstanceOfType(object)) { + length = object.length; + for (i = 0; i < length; i++) { + this._traceDump(object[i], '[' + i + ']', recursive, indentationPadding, loopArray); + } + } + else { + for (p in object) { + v = object[p]; + if (!Function.isInstanceOfType(v)) { + this._traceDump(v, p, recursive, indentationPadding, loopArray); + } + } + } + } + } + Array.remove(loopArray, object); + } + } +Sys._Debug.prototype = { + _appendConsole: Sys$_Debug$_appendConsole, + _appendTrace: Sys$_Debug$_appendTrace, + assert: Sys$_Debug$assert, + clearTrace: Sys$_Debug$clearTrace, + fail: Sys$_Debug$fail, + trace: Sys$_Debug$trace, + traceDump: Sys$_Debug$traceDump, + _traceDump: Sys$_Debug$_traceDump +} +Sys._Debug.registerClass('Sys._Debug'); +Sys.Debug = new Sys._Debug(); + Sys.Debug.isDebug = true; + +function Sys$Enum$parse(value, ignoreCase) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String}, + {name: "ignoreCase", type: Boolean, optional: true} + ]); + if (e) throw e; + var values, parsed, val; + if (ignoreCase) { + values = this.__lowerCaseValues; + if (!values) { + this.__lowerCaseValues = values = {}; + var prototype = this.prototype; + for (var name in prototype) { + values[name.toLowerCase()] = prototype[name]; + } + } + } + else { + values = this.prototype; + } + if (!this.__flags) { + val = (ignoreCase ? value.toLowerCase() : value); + parsed = values[val.trim()]; + if (typeof(parsed) !== 'number') throw Error.argument('value', String.format(Sys.Res.enumInvalidValue, value, this.__typeName)); + return parsed; + } + else { + var parts = (ignoreCase ? value.toLowerCase() : value).split(','); + var v = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var part = parts[i].trim(); + parsed = values[part]; + if (typeof(parsed) !== 'number') throw Error.argument('value', String.format(Sys.Res.enumInvalidValue, value.split(',')[i].trim(), this.__typeName)); + v |= parsed; + } + return v; + } +} +function Sys$Enum$toString(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if ((typeof(value) === 'undefined') || (value === null)) return this.__string; + if ((typeof(value) != 'number') || ((value % 1) !== 0)) throw Error.argumentType('value', Object.getType(value), this); + var values = this.prototype; + var i; + if (!this.__flags || (value === 0)) { + for (i in values) { + if (values[i] === value) { + return i; + } + } + } + else { + var sorted = this.__sortedValues; + if (!sorted) { + sorted = []; + for (i in values) { + sorted[sorted.length] = {key: i, value: values[i]}; + } + sorted.sort(function(a, b) { + return a.value - b.value; + }); + this.__sortedValues = sorted; + } + var parts = []; + var v = value; + for (i = sorted.length - 1; i >= 0; i--) { + var kvp = sorted[i]; + var vali = kvp.value; + if (vali === 0) continue; + if ((vali & value) === vali) { + parts[parts.length] = kvp.key; + v -= vali; + if (v === 0) break; + } + } + if (parts.length && v === 0) return parts.reverse().join(', '); + } + throw Error.argumentOutOfRange('value', value, String.format(Sys.Res.enumInvalidValue, value, this.__typeName)); +} +Type.prototype.registerEnum = function Type$registerEnum(name, flags) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "name", type: String}, + {name: "flags", type: Boolean, optional: true} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(name)) throw Error.argument('name', Sys.Res.notATypeName); + var parsedName; + try { + parsedName = eval(name); + } + catch(e) { + throw Error.argument('name', Sys.Res.argumentTypeName); + } + if (parsedName !== this) throw Error.argument('name', Sys.Res.badTypeName); + if (Sys.__registeredTypes[name]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, name)); + for (var i in this.prototype) { + var val = this.prototype[i]; + if (!Type.__identifierRegExp.test(i)) throw Error.invalidOperation(String.format(Sys.Res.enumInvalidValueName, i)); + if (typeof(val) !== 'number' || (val % 1) !== 0) throw Error.invalidOperation(Sys.Res.enumValueNotInteger); + if (typeof(this[i]) !== 'undefined') throw Error.invalidOperation(String.format(Sys.Res.enumReservedName, i)); + } + Sys.__upperCaseTypes[name.toUpperCase()] = this; + for (var i in this.prototype) { + this[i] = this.prototype[i]; + } + this.__typeName = name; + this.parse = Sys$Enum$parse; + this.__string = this.toString(); + this.toString = Sys$Enum$toString; + this.__flags = flags; + this.__enum = true; + Sys.__registeredTypes[name] = true; +} +Type.isEnum = function Type$isEnum(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__enum; +} +Type.isFlags = function Type$isFlags(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__flags; +} + +Sys.EventHandlerList = function Sys$EventHandlerList() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._list = {}; +} + function Sys$EventHandlerList$addHandler(id, handler) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + Array.add(this._getEvent(id, true), handler); + } + function Sys$EventHandlerList$removeHandler(id, handler) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + var evt = this._getEvent(id); + if (!evt) return; + Array.remove(evt, handler); + } + function Sys$EventHandlerList$getHandler(id) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String} + ]); + if (e) throw e; + var evt = this._getEvent(id); + if (!evt || (evt.length === 0)) return null; + evt = Array.clone(evt); + return function(source, args) { + for (var i = 0, l = evt.length; i < l; i++) { + evt[i](source, args); + } + }; + } + function Sys$EventHandlerList$_getEvent(id, create) { + if (!this._list[id]) { + if (!create) return null; + this._list[id] = []; + } + return this._list[id]; + } +Sys.EventHandlerList.prototype = { + addHandler: Sys$EventHandlerList$addHandler, + removeHandler: Sys$EventHandlerList$removeHandler, + getHandler: Sys$EventHandlerList$getHandler, + _getEvent: Sys$EventHandlerList$_getEvent +} +Sys.EventHandlerList.registerClass('Sys.EventHandlerList'); + +Sys.EventArgs = function Sys$EventArgs() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} +Sys.EventArgs.registerClass('Sys.EventArgs'); +Sys.EventArgs.Empty = new Sys.EventArgs(); + +Sys.CancelEventArgs = function Sys$CancelEventArgs() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.CancelEventArgs.initializeBase(this); + this._cancel = false; +} + function Sys$CancelEventArgs$get_cancel() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._cancel; + } + function Sys$CancelEventArgs$set_cancel(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); + if (e) throw e; + this._cancel = value; + } +Sys.CancelEventArgs.prototype = { + get_cancel: Sys$CancelEventArgs$get_cancel, + set_cancel: Sys$CancelEventArgs$set_cancel +} +Sys.CancelEventArgs.registerClass('Sys.CancelEventArgs', Sys.EventArgs); + +Sys.INotifyPropertyChange = function Sys$INotifyPropertyChange() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} + function Sys$INotifyPropertyChange$add_propertyChanged(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$INotifyPropertyChange$remove_propertyChanged(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } +Sys.INotifyPropertyChange.prototype = { + add_propertyChanged: Sys$INotifyPropertyChange$add_propertyChanged, + remove_propertyChanged: Sys$INotifyPropertyChange$remove_propertyChanged +} +Sys.INotifyPropertyChange.registerInterface('Sys.INotifyPropertyChange'); + +Sys.PropertyChangedEventArgs = function Sys$PropertyChangedEventArgs(propertyName) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyName", type: String} + ]); + if (e) throw e; + Sys.PropertyChangedEventArgs.initializeBase(this); + this._propertyName = propertyName; +} + + function Sys$PropertyChangedEventArgs$get_propertyName() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._propertyName; + } +Sys.PropertyChangedEventArgs.prototype = { + get_propertyName: Sys$PropertyChangedEventArgs$get_propertyName +} +Sys.PropertyChangedEventArgs.registerClass('Sys.PropertyChangedEventArgs', Sys.EventArgs); + +Sys.INotifyDisposing = function Sys$INotifyDisposing() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} + function Sys$INotifyDisposing$add_disposing(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$INotifyDisposing$remove_disposing(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } +Sys.INotifyDisposing.prototype = { + add_disposing: Sys$INotifyDisposing$add_disposing, + remove_disposing: Sys$INotifyDisposing$remove_disposing +} +Sys.INotifyDisposing.registerInterface("Sys.INotifyDisposing"); + +Sys.Component = function Sys$Component() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (Sys.Application) Sys.Application.registerDisposableObject(this); +} + function Sys$Component$get_events() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._events) { + this._events = new Sys.EventHandlerList(); + } + return this._events; + } + function Sys$Component$get_id() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._id; + } + function Sys$Component$set_id(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + if (this._idSet) throw Error.invalidOperation(Sys.Res.componentCantSetIdTwice); + this._idSet = true; + var oldId = this.get_id(); + if (oldId && Sys.Application.findComponent(oldId)) throw Error.invalidOperation(Sys.Res.componentCantSetIdAfterAddedToApp); + this._id = value; + } + function Sys$Component$get_isInitialized() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._initialized; + } + function Sys$Component$get_isUpdating() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._updating; + } + function Sys$Component$add_disposing(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("disposing", handler); + } + function Sys$Component$remove_disposing(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("disposing", handler); + } + function Sys$Component$add_propertyChanged(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("propertyChanged", handler); + } + function Sys$Component$remove_propertyChanged(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("propertyChanged", handler); + } + function Sys$Component$beginUpdate() { + this._updating = true; + } + function Sys$Component$dispose() { + if (this._events) { + var handler = this._events.getHandler("disposing"); + if (handler) { + handler(this, Sys.EventArgs.Empty); + } + } + delete this._events; + Sys.Application.unregisterDisposableObject(this); + Sys.Application.removeComponent(this); + } + function Sys$Component$endUpdate() { + this._updating = false; + if (!this._initialized) this.initialize(); + this.updated(); + } + function Sys$Component$initialize() { + this._initialized = true; + } + function Sys$Component$raisePropertyChanged(propertyName) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyName", type: String} + ]); + if (e) throw e; + if (!this._events) return; + var handler = this._events.getHandler("propertyChanged"); + if (handler) { + handler(this, new Sys.PropertyChangedEventArgs(propertyName)); + } + } + function Sys$Component$updated() { + } +Sys.Component.prototype = { + _id: null, + _idSet: false, + _initialized: false, + _updating: false, + get_events: Sys$Component$get_events, + get_id: Sys$Component$get_id, + set_id: Sys$Component$set_id, + get_isInitialized: Sys$Component$get_isInitialized, + get_isUpdating: Sys$Component$get_isUpdating, + add_disposing: Sys$Component$add_disposing, + remove_disposing: Sys$Component$remove_disposing, + add_propertyChanged: Sys$Component$add_propertyChanged, + remove_propertyChanged: Sys$Component$remove_propertyChanged, + beginUpdate: Sys$Component$beginUpdate, + dispose: Sys$Component$dispose, + endUpdate: Sys$Component$endUpdate, + initialize: Sys$Component$initialize, + raisePropertyChanged: Sys$Component$raisePropertyChanged, + updated: Sys$Component$updated +} +Sys.Component.registerClass('Sys.Component', null, Sys.IDisposable, Sys.INotifyPropertyChange, Sys.INotifyDisposing); +function Sys$Component$_setProperties(target, properties) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "target"}, + {name: "properties"} + ]); + if (e) throw e; + var current; + var targetType = Object.getType(target); + var isObject = (targetType === Object) || (targetType === Sys.UI.DomElement); + var isComponent = Sys.Component.isInstanceOfType(target) && !target.get_isUpdating(); + if (isComponent) target.beginUpdate(); + for (var name in properties) { + var val = properties[name]; + var getter = isObject ? null : target["get_" + name]; + if (isObject || typeof(getter) !== 'function') { + var targetVal = target[name]; + if (!isObject && typeof(targetVal) === 'undefined') throw Error.invalidOperation(String.format(Sys.Res.propertyUndefined, name)); + if (!val || (typeof(val) !== 'object') || (isObject && !targetVal)) { + target[name] = val; + } + else { + Sys$Component$_setProperties(targetVal, val); + } + } + else { + var setter = target["set_" + name]; + if (typeof(setter) === 'function') { + setter.apply(target, [val]); + } + else if (val instanceof Array) { + current = getter.apply(target); + if (!(current instanceof Array)) throw new Error.invalidOperation(String.format(Sys.Res.propertyNotAnArray, name)); + for (var i = 0, j = current.length, l= val.length; i < l; i++, j++) { + current[j] = val[i]; + } + } + else if ((typeof(val) === 'object') && (Object.getType(val) === Object)) { + current = getter.apply(target); + if ((typeof(current) === 'undefined') || (current === null)) throw new Error.invalidOperation(String.format(Sys.Res.propertyNullOrUndefined, name)); + Sys$Component$_setProperties(current, val); + } + else { + throw new Error.invalidOperation(String.format(Sys.Res.propertyNotWritable, name)); + } + } + } + if (isComponent) target.endUpdate(); +} +function Sys$Component$_setReferences(component, references) { + for (var name in references) { + var setter = component["set_" + name]; + var reference = $find(references[name]); + if (typeof(setter) !== 'function') throw new Error.invalidOperation(String.format(Sys.Res.propertyNotWritable, name)); + if (!reference) throw Error.invalidOperation(String.format(Sys.Res.referenceNotFound, references[name])); + setter.apply(component, [reference]); + } +} +var $create = Sys.Component.create = function Sys$Component$create(type, properties, events, references, element) { + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", type: Type}, + {name: "properties", mayBeNull: true, optional: true}, + {name: "events", mayBeNull: true, optional: true}, + {name: "references", mayBeNull: true, optional: true}, + {name: "element", mayBeNull: true, domElement: true, optional: true} + ]); + if (e) throw e; + if (!type.inheritsFrom(Sys.Component)) { + throw Error.argument('type', String.format(Sys.Res.createNotComponent, type.getName())); + } + if (type.inheritsFrom(Sys.UI.Behavior) || type.inheritsFrom(Sys.UI.Control)) { + if (!element) throw Error.argument('element', Sys.Res.createNoDom); + } + else if (element) throw Error.argument('element', Sys.Res.createComponentOnDom); + var component = (element ? new type(element): new type()); + var app = Sys.Application; + var creatingComponents = app.get_isCreatingComponents(); + component.beginUpdate(); + if (properties) { + Sys$Component$_setProperties(component, properties); + } + if (events) { + for (var name in events) { + if (!(component["add_" + name] instanceof Function)) throw new Error.invalidOperation(String.format(Sys.Res.undefinedEvent, name)); + if (!(events[name] instanceof Function)) throw new Error.invalidOperation(Sys.Res.eventHandlerNotFunction); + component["add_" + name](events[name]); + } + } + if (component.get_id()) { + app.addComponent(component); + } + if (creatingComponents) { + app._createdComponents[app._createdComponents.length] = component; + if (references) { + app._addComponentToSecondPass(component, references); + } + else { + component.endUpdate(); + } + } + else { + if (references) { + Sys$Component$_setReferences(component, references); + } + component.endUpdate(); + } + return component; +} + +Sys.UI.MouseButton = function Sys$UI$MouseButton() { + /// + /// + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.MouseButton.prototype = { + leftButton: 0, + middleButton: 1, + rightButton: 2 +} +Sys.UI.MouseButton.registerEnum("Sys.UI.MouseButton"); + +Sys.UI.Key = function Sys$UI$Key() { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.Key.prototype = { + backspace: 8, + tab: 9, + enter: 13, + esc: 27, + space: 32, + pageUp: 33, + pageDown: 34, + end: 35, + home: 36, + left: 37, + up: 38, + right: 39, + down: 40, + del: 127 +} +Sys.UI.Key.registerEnum("Sys.UI.Key"); + +Sys.UI.Point = function Sys$UI$Point(x, y) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "x", type: Number, integer: true}, + {name: "y", type: Number, integer: true} + ]); + if (e) throw e; + this.x = x; + this.y = y; +} +Sys.UI.Point.registerClass('Sys.UI.Point'); + +Sys.UI.Bounds = function Sys$UI$Bounds(x, y, width, height) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "x", type: Number, integer: true}, + {name: "y", type: Number, integer: true}, + {name: "height", type: Number, integer: true}, + {name: "width", type: Number, integer: true} + ]); + if (e) throw e; + this.x = x; + this.y = y; + this.height = height; + this.width = width; +} +Sys.UI.Bounds.registerClass('Sys.UI.Bounds'); + +Sys.UI.DomEvent = function Sys$UI$DomEvent(eventObject) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "eventObject"} + ]); + if (e) throw e; + var e = eventObject; + var etype = this.type = e.type.toLowerCase(); + this.rawEvent = e; + this.altKey = e.altKey; + if (typeof(e.button) !== 'undefined') { + this.button = (typeof(e.which) !== 'undefined') ? e.button : + (e.button === 4) ? Sys.UI.MouseButton.middleButton : + (e.button === 2) ? Sys.UI.MouseButton.rightButton : + Sys.UI.MouseButton.leftButton; + } + if (etype === 'keypress') { + this.charCode = e.charCode || e.keyCode; + } + else if (e.keyCode && (e.keyCode === 46)) { + this.keyCode = 127; + } + else { + this.keyCode = e.keyCode; + } + this.clientX = e.clientX; + this.clientY = e.clientY; + this.ctrlKey = e.ctrlKey; + this.target = e.target ? e.target : e.srcElement; + if (!etype.startsWith('key')) { + if ((typeof(e.offsetX) !== 'undefined') && (typeof(e.offsetY) !== 'undefined')) { + this.offsetX = e.offsetX; + this.offsetY = e.offsetY; + } + else if (this.target && (this.target.nodeType !== 3) && (typeof(e.clientX) === 'number')) { + var loc = Sys.UI.DomElement.getLocation(this.target); + var w = Sys.UI.DomElement._getWindow(this.target); + this.offsetX = (w.pageXOffset || 0) + e.clientX - loc.x; + this.offsetY = (w.pageYOffset || 0) + e.clientY - loc.y; + } + } + this.screenX = e.screenX; + this.screenY = e.screenY; + this.shiftKey = e.shiftKey; +} + function Sys$UI$DomEvent$preventDefault() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this.rawEvent.preventDefault) { + this.rawEvent.preventDefault(); + } + else if (window.event) { + this.rawEvent.returnValue = false; + } + } + function Sys$UI$DomEvent$stopPropagation() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this.rawEvent.stopPropagation) { + this.rawEvent.stopPropagation(); + } + else if (window.event) { + this.rawEvent.cancelBubble = true; + } + } +Sys.UI.DomEvent.prototype = { + preventDefault: Sys$UI$DomEvent$preventDefault, + stopPropagation: Sys$UI$DomEvent$stopPropagation +} +Sys.UI.DomEvent.registerClass('Sys.UI.DomEvent'); +var $addHandler = Sys.UI.DomEvent.addHandler = function Sys$UI$DomEvent$addHandler(element, eventName, handler) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"}, + {name: "eventName", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + if (eventName === "error") throw Error.invalidOperation(Sys.Res.addHandlerCantBeUsedForError); + if (!element._events) { + element._events = {}; + } + var eventCache = element._events[eventName]; + if (!eventCache) { + element._events[eventName] = eventCache = []; + } + var browserHandler; + if (element.addEventListener) { + browserHandler = function(e) { + return handler.call(element, new Sys.UI.DomEvent(e)); + } + element.addEventListener(eventName, browserHandler, false); + } + else if (element.attachEvent) { + browserHandler = function() { + var e = {}; + try {e = Sys.UI.DomElement._getWindow(element).event} catch(ex) {} + return handler.call(element, new Sys.UI.DomEvent(e)); + } + element.attachEvent('on' + eventName, browserHandler); + } + eventCache[eventCache.length] = {handler: handler, browserHandler: browserHandler}; +} +var $addHandlers = Sys.UI.DomEvent.addHandlers = function Sys$UI$DomEvent$addHandlers(element, events, handlerOwner) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"}, + {name: "events", type: Object}, + {name: "handlerOwner", optional: true} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + for (var name in events) { + var handler = events[name]; + if (typeof(handler) !== 'function') throw Error.invalidOperation(Sys.Res.cantAddNonFunctionhandler); + if (handlerOwner) { + handler = Function.createDelegate(handlerOwner, handler); + } + $addHandler(element, name, handler); + } +} +var $clearHandlers = Sys.UI.DomEvent.clearHandlers = function Sys$UI$DomEvent$clearHandlers(element) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + if (element._events) { + var cache = element._events; + for (var name in cache) { + var handlers = cache[name]; + for (var i = handlers.length - 1; i >= 0; i--) { + $removeHandler(element, name, handlers[i].handler); + } + } + element._events = null; + } +} +var $removeHandler = Sys.UI.DomEvent.removeHandler = function Sys$UI$DomEvent$removeHandler(element, eventName, handler) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"}, + {name: "eventName", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + var browserHandler = null; + if ((typeof(element._events) !== 'object') || (element._events == null)) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); + var cache = element._events[eventName]; + if (!(cache instanceof Array)) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); + for (var i = 0, l = cache.length; i < l; i++) { + if (cache[i].handler === handler) { + browserHandler = cache[i].browserHandler; + break; + } + } + if (typeof(browserHandler) !== 'function') throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); + if (element.removeEventListener) { + element.removeEventListener(eventName, browserHandler, false); + } + else if (element.detachEvent) { + element.detachEvent('on' + eventName, browserHandler); + } + cache.splice(i, 1); +} +Sys.UI.DomEvent._ensureDomNode = function Sys$UI$DomEvent$_ensureDomNode(element) { + if (element.tagName && (element.tagName.toUpperCase() === "SCRIPT")) return; + + var doc = element.ownerDocument || element.document || element; + if ((typeof(element.document) !== 'object') && (element != doc) && (typeof(element.nodeType) !== 'number')) { + throw Error.argument("element", Sys.Res.argumentDomNode); + } +} + +Sys.UI.DomElement = function Sys$UI$DomElement() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.DomElement.registerClass('Sys.UI.DomElement'); +Sys.UI.DomElement.addCssClass = function Sys$UI$DomElement$addCssClass(element, className) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + if (!Sys.UI.DomElement.containsCssClass(element, className)) { + if (element.className === '') { + element.className = className; + } + else { + element.className += ' ' + className; + } + } +} +Sys.UI.DomElement.containsCssClass = function Sys$UI$DomElement$containsCssClass(element, className) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + return Array.contains(element.className.split(' '), className); +} +Sys.UI.DomElement.getBounds = function Sys$UI$DomElement$getBounds(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + var offset = Sys.UI.DomElement.getLocation(element); + return new Sys.UI.Bounds(offset.x, offset.y, element.offsetWidth || 0, element.offsetHeight || 0); +} +var $get = Sys.UI.DomElement.getElementById = function Sys$UI$DomElement$getElementById(id, element) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "element", mayBeNull: true, domElement: true, optional: true} + ]); + if (e) throw e; + if (!element) return document.getElementById(id); + if (element.getElementById) return element.getElementById(id); + var nodeQueue = []; + var childNodes = element.childNodes; + for (var i = 0; i < childNodes.length; i++) { + var node = childNodes[i]; + if (node.nodeType == 1) { + nodeQueue[nodeQueue.length] = node; + } + } + while (nodeQueue.length) { + node = nodeQueue.shift(); + if (node.id == id) { + return node; + } + childNodes = node.childNodes; + for (i = 0; i < childNodes.length; i++) { + node = childNodes[i]; + if (node.nodeType == 1) { + nodeQueue[nodeQueue.length] = node; + } + } + } + return null; +} +switch(Sys.Browser.agent) { + case Sys.Browser.InternetExplorer: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if (element.self || element.nodeType === 9) return new Sys.UI.Point(0,0); + var clientRect = element.getBoundingClientRect(); + if (!clientRect) { + return new Sys.UI.Point(0,0); + } + var documentElement = element.ownerDocument.documentElement; + var offsetX = clientRect.left - 2 + documentElement.scrollLeft, + offsetY = clientRect.top - 2 + documentElement.scrollTop; + + try { + var f = element.ownerDocument.parentWindow.frameElement || null; + if (f) { + var offset = (f.frameBorder === "0" || f.frameBorder === "no") ? 2 : 0; + offsetX += offset; + offsetY += offset; + } + } + catch(ex) { + } + + return new Sys.UI.Point(offsetX, offsetY); + } + break; + case Sys.Browser.Safari: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); + var offsetX = 0; + var offsetY = 0; + var previous = null; + var previousStyle = null; + var currentStyle; + for (var parent = element; parent; previous = parent, previousStyle = currentStyle, parent = parent.offsetParent) { + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + var tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + if ((parent.offsetLeft || parent.offsetTop) && + ((tagName !== "BODY") || (!previousStyle || previousStyle.position !== "absolute"))) { + offsetX += parent.offsetLeft; + offsetY += parent.offsetTop; + } + } + currentStyle = Sys.UI.DomElement._getCurrentStyle(element); + var elementPosition = currentStyle ? currentStyle.position : null; + if (!elementPosition || (elementPosition !== "absolute")) { + for (var parent = element.parentNode; parent; parent = parent.parentNode) { + tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop)) { + offsetX -= (parent.scrollLeft || 0); + offsetY -= (parent.scrollTop || 0); + } + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + var parentPosition = currentStyle ? currentStyle.position : null; + if (parentPosition && (parentPosition === "absolute")) break; + } + } + return new Sys.UI.Point(offsetX, offsetY); + } + break; + case Sys.Browser.Opera: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); + var offsetX = 0; + var offsetY = 0; + var previous = null; + for (var parent = element; parent; previous = parent, parent = parent.offsetParent) { + var tagName = parent.tagName; + offsetX += parent.offsetLeft || 0; + offsetY += parent.offsetTop || 0; + } + var elementPosition = element.style.position; + var elementPositioned = elementPosition && (elementPosition !== "static"); + for (var parent = element.parentNode; parent; parent = parent.parentNode) { + tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop) && + ((elementPositioned && + ((parent.style.overflow === "scroll") || (parent.style.overflow === "auto"))))) { + offsetX -= (parent.scrollLeft || 0); + offsetY -= (parent.scrollTop || 0); + } + var parentPosition = (parent && parent.style) ? parent.style.position : null; + elementPositioned = elementPositioned || (parentPosition && (parentPosition !== "static")); + } + return new Sys.UI.Point(offsetX, offsetY); + } + break; + default: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); + var offsetX = 0; + var offsetY = 0; + var previous = null; + var previousStyle = null; + var currentStyle = null; + for (var parent = element; parent; previous = parent, previousStyle = currentStyle, parent = parent.offsetParent) { + var tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + if ((parent.offsetLeft || parent.offsetTop) && + !((tagName === "BODY") && + (!previousStyle || previousStyle.position !== "absolute"))) { + offsetX += parent.offsetLeft; + offsetY += parent.offsetTop; + } + if (previous !== null && currentStyle) { + if ((tagName !== "TABLE") && (tagName !== "TD") && (tagName !== "HTML")) { + offsetX += parseInt(currentStyle.borderLeftWidth) || 0; + offsetY += parseInt(currentStyle.borderTopWidth) || 0; + } + if (tagName === "TABLE" && + (currentStyle.position === "relative" || currentStyle.position === "absolute")) { + offsetX += parseInt(currentStyle.marginLeft) || 0; + offsetY += parseInt(currentStyle.marginTop) || 0; + } + } + } + currentStyle = Sys.UI.DomElement._getCurrentStyle(element); + var elementPosition = currentStyle ? currentStyle.position : null; + if (!elementPosition || (elementPosition !== "absolute")) { + for (var parent = element.parentNode; parent; parent = parent.parentNode) { + tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop)) { + offsetX -= (parent.scrollLeft || 0); + offsetY -= (parent.scrollTop || 0); + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + if (currentStyle) { + offsetX += parseInt(currentStyle.borderLeftWidth) || 0; + offsetY += parseInt(currentStyle.borderTopWidth) || 0; + } + } + } + } + return new Sys.UI.Point(offsetX, offsetY); + } + break; +} +Sys.UI.DomElement.removeCssClass = function Sys$UI$DomElement$removeCssClass(element, className) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + var currentClassName = ' ' + element.className + ' '; + var index = currentClassName.indexOf(' ' + className + ' '); + if (index >= 0) { + element.className = (currentClassName.substr(0, index) + ' ' + + currentClassName.substring(index + className.length + 1, currentClassName.length)).trim(); + } +} +Sys.UI.DomElement.setLocation = function Sys$UI$DomElement$setLocation(element, x, y) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "x", type: Number, integer: true}, + {name: "y", type: Number, integer: true} + ]); + if (e) throw e; + var style = element.style; + style.position = 'absolute'; + style.left = x + "px"; + style.top = y + "px"; +} +Sys.UI.DomElement.toggleCssClass = function Sys$UI$DomElement$toggleCssClass(element, className) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + if (Sys.UI.DomElement.containsCssClass(element, className)) { + Sys.UI.DomElement.removeCssClass(element, className); + } + else { + Sys.UI.DomElement.addCssClass(element, className); + } +} +Sys.UI.DomElement.getVisibilityMode = function Sys$UI$DomElement$getVisibilityMode(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + return (element._visibilityMode === Sys.UI.VisibilityMode.hide) ? + Sys.UI.VisibilityMode.hide : + Sys.UI.VisibilityMode.collapse; +} +Sys.UI.DomElement.setVisibilityMode = function Sys$UI$DomElement$setVisibilityMode(element, value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "value", type: Sys.UI.VisibilityMode} + ]); + if (e) throw e; + Sys.UI.DomElement._ensureOldDisplayMode(element); + if (element._visibilityMode !== value) { + element._visibilityMode = value; + if (Sys.UI.DomElement.getVisible(element) === false) { + if (element._visibilityMode === Sys.UI.VisibilityMode.hide) { + element.style.display = element._oldDisplayMode; + } + else { + element.style.display = 'none'; + } + } + element._visibilityMode = value; + } +} +Sys.UI.DomElement.getVisible = function Sys$UI$DomElement$getVisible(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + var style = element.currentStyle || Sys.UI.DomElement._getCurrentStyle(element); + if (!style) return true; + return (style.visibility !== 'hidden') && (style.display !== 'none'); +} +Sys.UI.DomElement.setVisible = function Sys$UI$DomElement$setVisible(element, value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "value", type: Boolean} + ]); + if (e) throw e; + if (value !== Sys.UI.DomElement.getVisible(element)) { + Sys.UI.DomElement._ensureOldDisplayMode(element); + element.style.visibility = value ? 'visible' : 'hidden'; + if (value || (element._visibilityMode === Sys.UI.VisibilityMode.hide)) { + element.style.display = element._oldDisplayMode; + } + else { + element.style.display = 'none'; + } + } +} +Sys.UI.DomElement._ensureOldDisplayMode = function Sys$UI$DomElement$_ensureOldDisplayMode(element) { + if (!element._oldDisplayMode) { + var style = element.currentStyle || Sys.UI.DomElement._getCurrentStyle(element); + element._oldDisplayMode = style ? style.display : null; + if (!element._oldDisplayMode || element._oldDisplayMode === 'none') { + switch(element.tagName.toUpperCase()) { + case 'DIV': case 'P': case 'ADDRESS': case 'BLOCKQUOTE': case 'BODY': case 'COL': + case 'COLGROUP': case 'DD': case 'DL': case 'DT': case 'FIELDSET': case 'FORM': + case 'H1': case 'H2': case 'H3': case 'H4': case 'H5': case 'H6': case 'HR': + case 'IFRAME': case 'LEGEND': case 'OL': case 'PRE': case 'TABLE': case 'TD': + case 'TH': case 'TR': case 'UL': + element._oldDisplayMode = 'block'; + break; + case 'LI': + element._oldDisplayMode = 'list-item'; + break; + default: + element._oldDisplayMode = 'inline'; + } + } + } +} +Sys.UI.DomElement._getWindow = function Sys$UI$DomElement$_getWindow(element) { + var doc = element.ownerDocument || element.document || element; + return doc.defaultView || doc.parentWindow; +} +Sys.UI.DomElement._getCurrentStyle = function Sys$UI$DomElement$_getCurrentStyle(element) { + if (element.nodeType === 3) return null; + var w = Sys.UI.DomElement._getWindow(element); + if (element.documentElement) element = element.documentElement; + var computedStyle = (w && (element !== w) && w.getComputedStyle) ? + w.getComputedStyle(element, null) : + element.currentStyle || element.style; + if (!computedStyle && (Sys.Browser.agent === Sys.Browser.Safari) && element.style) { + var oldDisplay = element.style.display; + var oldPosition = element.style.position; + element.style.position = 'absolute'; + element.style.display = 'block'; + var style = w.getComputedStyle(element, null); + element.style.display = oldDisplay; + element.style.position = oldPosition; + computedStyle = {}; + for (var n in style) { + computedStyle[n] = style[n]; + } + computedStyle.display = 'none'; + } + return computedStyle; +} + +Sys.IContainer = function Sys$IContainer() { + throw Error.notImplemented(); +} + function Sys$IContainer$addComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$IContainer$removeComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$IContainer$findComponent(id) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$IContainer$getComponents() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } +Sys.IContainer.prototype = { + addComponent: Sys$IContainer$addComponent, + removeComponent: Sys$IContainer$removeComponent, + findComponent: Sys$IContainer$findComponent, + getComponents: Sys$IContainer$getComponents +} +Sys.IContainer.registerInterface("Sys.IContainer"); + +Sys._ScriptLoader = function Sys$_ScriptLoader() { + this._scriptsToLoad = null; + this._sessions = []; + this._scriptLoadedDelegate = Function.createDelegate(this, this._scriptLoadedHandler); +} + function Sys$_ScriptLoader$dispose() { + this._stopSession(); + this._loading = false; + if(this._events) { + delete this._events; + } + this._sessions = null; + this._currentSession = null; + this._scriptLoadedDelegate = null; + } + function Sys$_ScriptLoader$loadScripts(scriptTimeout, allScriptsLoadedCallback, scriptLoadFailedCallback, scriptLoadTimeoutCallback) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptTimeout", type: Number, integer: true}, + {name: "allScriptsLoadedCallback", type: Function, mayBeNull: true}, + {name: "scriptLoadFailedCallback", type: Function, mayBeNull: true}, + {name: "scriptLoadTimeoutCallback", type: Function, mayBeNull: true} + ]); + if (e) throw e; + var session = { + allScriptsLoadedCallback: allScriptsLoadedCallback, + scriptLoadFailedCallback: scriptLoadFailedCallback, + scriptLoadTimeoutCallback: scriptLoadTimeoutCallback, + scriptsToLoad: this._scriptsToLoad, + scriptTimeout: scriptTimeout }; + this._scriptsToLoad = null; + this._sessions[this._sessions.length] = session; + + if (!this._loading) { + this._nextSession(); + } + } + function Sys$_ScriptLoader$notifyScriptLoaded() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + + if(!this._loading) { + return; + } + this._currentTask._notified++; + + if(Sys.Browser.agent === Sys.Browser.Safari) { + if(this._currentTask._notified === 1) { + window.setTimeout(Function.createDelegate(this, function() { + this._scriptLoadedHandler(this._currentTask.get_scriptElement(), true); + }), 0); + } + } + } + function Sys$_ScriptLoader$queueCustomScriptTag(scriptAttributes) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptAttributes"} + ]); + if (e) throw e; + if(!this._scriptsToLoad) { + this._scriptsToLoad = []; + } + Array.add(this._scriptsToLoad, scriptAttributes); + } + function Sys$_ScriptLoader$queueScriptBlock(scriptContent) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptContent", type: String} + ]); + if (e) throw e; + if(!this._scriptsToLoad) { + this._scriptsToLoad = []; + } + Array.add(this._scriptsToLoad, {text: scriptContent}); + } + function Sys$_ScriptLoader$queueScriptReference(scriptUrl) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptUrl", type: String} + ]); + if (e) throw e; + if(!this._scriptsToLoad) { + this._scriptsToLoad = []; + } + Array.add(this._scriptsToLoad, {src: scriptUrl}); + } + function Sys$_ScriptLoader$_createScriptElement(queuedScript) { + var scriptElement = document.createElement('script'); + scriptElement.type = 'text/javascript'; + for (var attr in queuedScript) { + scriptElement[attr] = queuedScript[attr]; + } + + return scriptElement; + } + function Sys$_ScriptLoader$_loadScriptsInternal() { + var session = this._currentSession; + if (session.scriptsToLoad && session.scriptsToLoad.length > 0) { + var nextScript = Array.dequeue(session.scriptsToLoad); + var scriptElement = this._createScriptElement(nextScript); + + if (scriptElement.text && Sys.Browser.agent === Sys.Browser.Safari) { + scriptElement.innerHTML = scriptElement.text; + delete scriptElement.text; + } + if (typeof(nextScript.src) === "string") { + this._currentTask = new Sys._ScriptLoaderTask(scriptElement, this._scriptLoadedDelegate); + this._currentTask.execute(); + } + else { + var headElements = document.getElementsByTagName('head'); + if (headElements.length === 0) { + throw new Error.invalidOperation(Sys.Res.scriptLoadFailedNoHead); + } + else { + headElements[0].appendChild(scriptElement); + } + + + Sys._ScriptLoader._clearScript(scriptElement); + this._loadScriptsInternal(); + } + } + else { + this._stopSession(); + var callback = session.allScriptsLoadedCallback; + if(callback) { + callback(this); + } + this._nextSession(); + } + } + function Sys$_ScriptLoader$_nextSession() { + if (this._sessions.length === 0) { + this._loading = false; + this._currentSession = null; + return; + } + this._loading = true; + + var session = Array.dequeue(this._sessions); + this._currentSession = session; + this._loadScriptsInternal(); + } + function Sys$_ScriptLoader$_raiseError(multipleCallbacks) { + var callback = this._currentSession.scriptLoadFailedCallback; + var scriptElement = this._currentTask.get_scriptElement(); + this._stopSession(); + + if(callback) { + callback(this, scriptElement, multipleCallbacks); + this._nextSession(); + } + else { + this._loading = false; + throw Sys._ScriptLoader._errorScriptLoadFailed(scriptElement.src, multipleCallbacks); + } + } + function Sys$_ScriptLoader$_scriptLoadedHandler(scriptElement, loaded) { + if(loaded && this._currentTask._notified) { + if(this._currentTask._notified > 1) { + this._raiseError(true); + } + else { + Array.add(Sys._ScriptLoader._getLoadedScripts(), scriptElement.src); + this._currentTask.dispose(); + this._currentTask = null; + this._loadScriptsInternal(); + } + } + else { + this._raiseError(false); + } + } + function Sys$_ScriptLoader$_scriptLoadTimeoutHandler() { + var callback = this._currentSession.scriptLoadTimeoutCallback; + this._stopSession(); + if(callback) { + callback(this); + } + this._nextSession(); + } + function Sys$_ScriptLoader$_stopSession() { + if(this._currentTask) { + this._currentTask.dispose(); + this._currentTask = null; + } + } +Sys._ScriptLoader.prototype = { + dispose: Sys$_ScriptLoader$dispose, + loadScripts: Sys$_ScriptLoader$loadScripts, + notifyScriptLoaded: Sys$_ScriptLoader$notifyScriptLoaded, + queueCustomScriptTag: Sys$_ScriptLoader$queueCustomScriptTag, + queueScriptBlock: Sys$_ScriptLoader$queueScriptBlock, + queueScriptReference: Sys$_ScriptLoader$queueScriptReference, + _createScriptElement: Sys$_ScriptLoader$_createScriptElement, + _loadScriptsInternal: Sys$_ScriptLoader$_loadScriptsInternal, + _nextSession: Sys$_ScriptLoader$_nextSession, + _raiseError: Sys$_ScriptLoader$_raiseError, + _scriptLoadedHandler: Sys$_ScriptLoader$_scriptLoadedHandler, + _scriptLoadTimeoutHandler: Sys$_ScriptLoader$_scriptLoadTimeoutHandler, + _stopSession: Sys$_ScriptLoader$_stopSession +} +Sys._ScriptLoader.registerClass('Sys._ScriptLoader', null, Sys.IDisposable); +Sys._ScriptLoader.getInstance = function Sys$_ScriptLoader$getInstance() { + var sl = Sys._ScriptLoader._activeInstance; + if(!sl) { + sl = Sys._ScriptLoader._activeInstance = new Sys._ScriptLoader(); + } + return sl; +} +Sys._ScriptLoader.isScriptLoaded = function Sys$_ScriptLoader$isScriptLoaded(scriptSrc) { + var dummyScript = document.createElement('script'); + dummyScript.src = scriptSrc; + return Array.contains(Sys._ScriptLoader._getLoadedScripts(), dummyScript.src); +} +Sys._ScriptLoader.readLoadedScripts = function Sys$_ScriptLoader$readLoadedScripts() { + if(!Sys._ScriptLoader._referencedScripts) { + var referencedScripts = Sys._ScriptLoader._referencedScripts = []; + var existingScripts = document.getElementsByTagName('script'); + for (i = existingScripts.length - 1; i >= 0; i--) { + var scriptNode = existingScripts[i]; + var scriptSrc = scriptNode.src; + if (scriptSrc.length) { + if (!Array.contains(referencedScripts, scriptSrc)) { + Array.add(referencedScripts, scriptSrc); + } + } + } + } +} +Sys._ScriptLoader._clearScript = function Sys$_ScriptLoader$_clearScript(scriptElement) { + if (!Sys.Debug.isDebug) { + scriptElement.parentNode.removeChild(scriptElement); + } +} +Sys._ScriptLoader._errorScriptLoadFailed = function Sys$_ScriptLoader$_errorScriptLoadFailed(scriptUrl, multipleCallbacks) { + var errorMessage; + if(multipleCallbacks) { + errorMessage = Sys.Res.scriptLoadMultipleCallbacks; + } + else { + errorMessage = Sys.Res.scriptLoadFailedDebug; + } + var displayMessage = "Sys.ScriptLoadFailedException: " + String.format(errorMessage, scriptUrl); + var e = Error.create(displayMessage, {name: 'Sys.ScriptLoadFailedException', 'scriptUrl': scriptUrl }); + e.popStackFrame(); + return e; +} +Sys._ScriptLoader._getLoadedScripts = function Sys$_ScriptLoader$_getLoadedScripts() { + if(!Sys._ScriptLoader._referencedScripts) { + Sys._ScriptLoader._referencedScripts = []; + Sys._ScriptLoader.readLoadedScripts(); + } + return Sys._ScriptLoader._referencedScripts; +} + +Sys._ScriptLoaderTask = function Sys$_ScriptLoaderTask(scriptElement, completedCallback) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptElement", domElement: true}, + {name: "completedCallback", type: Function} + ]); + if (e) throw e; + this._scriptElement = scriptElement; + this._completedCallback = completedCallback; + this._notified = 0; +} + function Sys$_ScriptLoaderTask$get_scriptElement() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._scriptElement; + } + function Sys$_ScriptLoaderTask$dispose() { + if(this._disposed) { + return; + } + this._disposed = true; + this._removeScriptElementHandlers(); + Sys._ScriptLoader._clearScript(this._scriptElement); + this._scriptElement = null; + } + function Sys$_ScriptLoaderTask$execute() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._addScriptElementHandlers(); + var headElements = document.getElementsByTagName('head'); + if (headElements.length === 0) { + throw new Error.invalidOperation(Sys.Res.scriptLoadFailedNoHead); + } + else { + headElements[0].appendChild(this._scriptElement); + } + } + function Sys$_ScriptLoaderTask$_addScriptElementHandlers() { + this._scriptLoadDelegate = Function.createDelegate(this, this._scriptLoadHandler); + + if (Sys.Browser.agent !== Sys.Browser.InternetExplorer) { + this._scriptElement.readyState = 'loaded'; + $addHandler(this._scriptElement, 'load', this._scriptLoadDelegate); + } + else { + $addHandler(this._scriptElement, 'readystatechange', this._scriptLoadDelegate); + } + if (this._scriptElement.addEventListener) { + this._scriptErrorDelegate = Function.createDelegate(this, this._scriptErrorHandler); + this._scriptElement.addEventListener('error', this._scriptErrorDelegate, false); + } + } + function Sys$_ScriptLoaderTask$_removeScriptElementHandlers() { + if(this._scriptLoadDelegate) { + var scriptElement = this.get_scriptElement(); + if (Sys.Browser.agent !== Sys.Browser.InternetExplorer) { + $removeHandler(scriptElement, 'load', this._scriptLoadDelegate); + } + else { + $removeHandler(scriptElement, 'readystatechange', this._scriptLoadDelegate); + } + if (this._scriptErrorDelegate) { + this._scriptElement.removeEventListener('error', this._scriptErrorDelegate, false); + this._scriptErrorDelegate = null; + } + this._scriptLoadDelegate = null; + } + } + function Sys$_ScriptLoaderTask$_scriptErrorHandler() { + if(this._disposed) { + return; + } + + this._completedCallback(this.get_scriptElement(), false); + } + function Sys$_ScriptLoaderTask$_scriptLoadHandler() { + if(this._disposed) { + return; + } + var scriptElement = this.get_scriptElement(); + if ((scriptElement.readyState !== 'loaded') && + (scriptElement.readyState !== 'complete')) { + return; + } + + var _this = this; + window.setTimeout(function() { + _this._completedCallback(scriptElement, true); + }, 0); + } +Sys._ScriptLoaderTask.prototype = { + get_scriptElement: Sys$_ScriptLoaderTask$get_scriptElement, + dispose: Sys$_ScriptLoaderTask$dispose, + execute: Sys$_ScriptLoaderTask$execute, + _addScriptElementHandlers: Sys$_ScriptLoaderTask$_addScriptElementHandlers, + _removeScriptElementHandlers: Sys$_ScriptLoaderTask$_removeScriptElementHandlers, + _scriptErrorHandler: Sys$_ScriptLoaderTask$_scriptErrorHandler, + _scriptLoadHandler: Sys$_ScriptLoaderTask$_scriptLoadHandler +} +Sys._ScriptLoaderTask.registerClass("Sys._ScriptLoaderTask", null, Sys.IDisposable); + +Sys.ApplicationLoadEventArgs = function Sys$ApplicationLoadEventArgs(components, isPartialLoad) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "components", type: Array, elementType: Sys.Component}, + {name: "isPartialLoad", type: Boolean} + ]); + if (e) throw e; + Sys.ApplicationLoadEventArgs.initializeBase(this); + this._components = components; + this._isPartialLoad = isPartialLoad; +} + + function Sys$ApplicationLoadEventArgs$get_components() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._components; + } + function Sys$ApplicationLoadEventArgs$get_isPartialLoad() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._isPartialLoad; + } +Sys.ApplicationLoadEventArgs.prototype = { + get_components: Sys$ApplicationLoadEventArgs$get_components, + get_isPartialLoad: Sys$ApplicationLoadEventArgs$get_isPartialLoad +} +Sys.ApplicationLoadEventArgs.registerClass('Sys.ApplicationLoadEventArgs', Sys.EventArgs); +Sys.HistoryEventArgs = function Sys$HistoryEventArgs(state) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "state", type: Object} + ]); + if (e) throw e; + Sys.HistoryEventArgs.initializeBase(this); + this._state = state; +} + function Sys$HistoryEventArgs$get_state() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._state; + } +Sys.HistoryEventArgs.prototype = { + get_state: Sys$HistoryEventArgs$get_state +} +Sys.HistoryEventArgs.registerClass('Sys.HistoryEventArgs', Sys.EventArgs); + +Sys._Application = function Sys$_Application() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys._Application.initializeBase(this); + this._disposableObjects = []; + this._components = {}; + this._createdComponents = []; + this._secondPassComponents = []; + this._appLoadHandler = null; + this._beginRequestHandler = null; + this._clientId = null; + this._currentEntry = ''; + this._endRequestHandler = null; + this._history = null; + this._enableHistory = false; + this._historyEnabledInScriptManager = false; + this._historyFrame = null; + this._historyInitialized = false; + this._historyInitialLength = 0; + this._historyLength = 0; + this._historyPointIsNew = false; + this._ignoreTimer = false; + this._initialState = null; + this._state = {}; + this._timerCookie = 0; + this._timerHandler = null; + this._uniqueId = null; + this._unloadHandlerDelegate = Function.createDelegate(this, this._unloadHandler); + this._loadHandlerDelegate = Function.createDelegate(this, this._loadHandler); + Sys.UI.DomEvent.addHandler(window, "unload", this._unloadHandlerDelegate); + Sys.UI.DomEvent.addHandler(window, "load", this._loadHandlerDelegate); +} + function Sys$_Application$get_isCreatingComponents() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._creatingComponents; + } + function Sys$_Application$get_stateString() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var hash = window.location.hash; + if (this._isSafari2()) { + var history = this._getHistory(); + if (history) { + hash = history[window.history.length - this._historyInitialLength]; + } + } + if ((hash.length > 0) && (hash.charAt(0) === '#')) { + hash = hash.substring(1); + } + if (Sys.Browser.agent === Sys.Browser.Firefox) { + hash = this._serializeState(this._deserializeState(hash, true)); + } + return hash; + } + function Sys$_Application$get_enableHistory() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._enableHistory; + } + function Sys$_Application$set_enableHistory(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); + if (e) throw e; + if (this._initialized && !this._initializing) { + throw Error.invalidOperation(Sys.Res.historyCannotEnableHistory); + } + else if (this._historyEnabledInScriptManager && !value) { + throw Error.invalidOperation(Sys.Res.invalidHistorySettingCombination); + } + this._enableHistory = value; + } + function Sys$_Application$add_init(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + if (this._initialized) { + handler(this, Sys.EventArgs.Empty); + } + else { + this.get_events().addHandler("init", handler); + } + } + function Sys$_Application$remove_init(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("init", handler); + } + function Sys$_Application$add_load(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("load", handler); + } + function Sys$_Application$remove_load(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("load", handler); + } + function Sys$_Application$add_navigate(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("navigate", handler); + } + function Sys$_Application$remove_navigate(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("navigate", handler); + } + function Sys$_Application$add_unload(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("unload", handler); + } + function Sys$_Application$remove_unload(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("unload", handler); + } + function Sys$_Application$addComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + var id = component.get_id(); + if (!id) throw Error.invalidOperation(Sys.Res.cantAddWithoutId); + if (typeof(this._components[id]) !== 'undefined') throw Error.invalidOperation(String.format(Sys.Res.appDuplicateComponent, id)); + this._components[id] = component; + } + function Sys$_Application$addHistoryPoint(state, title) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "state", type: Object}, + {name: "title", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (!this._enableHistory) throw Error.invalidOperation(Sys.Res.historyCannotAddHistoryPointWithHistoryDisabled); + for (var n in state) { + var v = state[n]; + var t = typeof(v); + if ((v !== null) && ((t === 'object') || (t === 'function') || (t === 'undefined'))) { + throw Error.argument('state', Sys.Res.stateMustBeStringDictionary); + } + } + this._ensureHistory(); + var initialState = this._state; + for (var key in state) { + var value = state[key]; + if (value === null) { + if (typeof(initialState[key]) !== 'undefined') { + delete initialState[key]; + } + } + else { + initialState[key] = value; + } + } + var entry = this._serializeState(initialState); + this._historyPointIsNew = true; + this._setState(entry, title); + this._raiseNavigate(); + } + function Sys$_Application$beginCreateComponents() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._creatingComponents = true; + } + function Sys$_Application$dispose() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._disposing) { + this._disposing = true; + if (this._timerCookie) { + window.clearTimeout(this._timerCookie); + delete this._timerCookie; + } + if (this._endRequestHandler) { + Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this._endRequestHandler); + delete this._endRequestHandler; + } + if (this._beginRequestHandler) { + Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(this._beginRequestHandler); + delete this._beginRequestHandler; + } + if (window.pageUnload) { + window.pageUnload(this, Sys.EventArgs.Empty); + } + var unloadHandler = this.get_events().getHandler("unload"); + if (unloadHandler) { + unloadHandler(this, Sys.EventArgs.Empty); + } + var disposableObjects = Array.clone(this._disposableObjects); + for (var i = 0, l = disposableObjects.length; i < l; i++) { + disposableObjects[i].dispose(); + } + Array.clear(this._disposableObjects); + Sys.UI.DomEvent.removeHandler(window, "unload", this._unloadHandlerDelegate); + if(this._loadHandlerDelegate) { + Sys.UI.DomEvent.removeHandler(window, "load", this._loadHandlerDelegate); + this._loadHandlerDelegate = null; + } + var sl = Sys._ScriptLoader.getInstance(); + if(sl) { + sl.dispose(); + } + Sys._Application.callBaseMethod(this, 'dispose'); + } + } + function Sys$_Application$endCreateComponents() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var components = this._secondPassComponents; + for (var i = 0, l = components.length; i < l; i++) { + var component = components[i].component; + Sys$Component$_setReferences(component, components[i].references); + component.endUpdate(); + } + this._secondPassComponents = []; + this._creatingComponents = false; + } + function Sys$_Application$findComponent(id, parent) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "parent", mayBeNull: true, optional: true} + ]); + if (e) throw e; + return (parent ? + ((Sys.IContainer.isInstanceOfType(parent)) ? + parent.findComponent(id) : + parent[id] || null) : + Sys.Application._components[id] || null); + } + function Sys$_Application$getComponents() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var res = []; + var components = this._components; + for (var name in components) { + res[res.length] = components[name]; + } + return res; + } + function Sys$_Application$initialize() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if(!this._initialized && !this._initializing) { + this._initializing = true; + window.setTimeout(Function.createDelegate(this, this._doInitialize), 0); + } + } + function Sys$_Application$notifyScriptLoaded() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var sl = Sys._ScriptLoader.getInstance(); + if(sl) { + sl.notifyScriptLoaded(); + } + } + function Sys$_Application$registerDisposableObject(object) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", type: Sys.IDisposable} + ]); + if (e) throw e; + if (!this._disposing) { + this._disposableObjects[this._disposableObjects.length] = object; + } + } + function Sys$_Application$raiseLoad() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var h = this.get_events().getHandler("load"); + var args = new Sys.ApplicationLoadEventArgs(Array.clone(this._createdComponents), !this._initializing); + if (h) { + h(this, args); + } + if (window.pageLoad) { + window.pageLoad(this, args); + } + this._createdComponents = []; + } + function Sys$_Application$removeComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + var id = component.get_id(); + if (id) delete this._components[id]; + } + function Sys$_Application$setServerId(clientId, uniqueId) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "clientId", type: String}, + {name: "uniqueId", type: String} + ]); + if (e) throw e; + this._clientId = clientId; + this._uniqueId = uniqueId; + } + function Sys$_Application$setServerState(value) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + this._ensureHistory(); + this._state.__s = value; + this._updateHiddenField(value); + } + function Sys$_Application$unregisterDisposableObject(object) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", type: Sys.IDisposable} + ]); + if (e) throw e; + if (!this._disposing) { + Array.remove(this._disposableObjects, object); + } + } + function Sys$_Application$_addComponentToSecondPass(component, references) { + this._secondPassComponents[this._secondPassComponents.length] = {component: component, references: references}; + } + function Sys$_Application$_deserializeState(entry, skipDecodeUri) { + var result = {}; + entry = entry || ''; + var serverSeparator = entry.indexOf('&&'); + if ((serverSeparator !== -1) && (serverSeparator + 2 < entry.length)) { + result.__s = entry.substr(serverSeparator + 2); + entry = entry.substr(0, serverSeparator); + } + var tokens = entry.split('&'); + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + var equal = token.indexOf('='); + if ((equal !== -1) && (equal + 1 < token.length)) { + var name = token.substr(0, equal); + var value = token.substr(equal + 1); + result[name] = skipDecodeUri ? value : decodeURIComponent(value); + } + } + return result; + } + function Sys$_Application$_doInitialize() { + Sys._Application.callBaseMethod(this, 'initialize'); + + var handler = this.get_events().getHandler("init"); + if (handler) { + this.beginCreateComponents(); + handler(this, Sys.EventArgs.Empty); + this.endCreateComponents(); + } + if (Sys.WebForms) { + this._beginRequestHandler = Function.createDelegate(this, this._onPageRequestManagerBeginRequest); + Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(this._beginRequestHandler); + this._endRequestHandler = Function.createDelegate(this, this._onPageRequestManagerEndRequest); + Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this._endRequestHandler); + } + + var loadedEntry = this.get_stateString(); + if (loadedEntry !== this._currentEntry) { + this._navigate(loadedEntry); + } + + this.raiseLoad(); + this._initializing = false; + } + function Sys$_Application$_enableHistoryInScriptManager() { + this._enableHistory = true; + this._historyEnabledInScriptManager = true; + } + function Sys$_Application$_ensureHistory() { + if (!this._historyInitialized && this._enableHistory) { + if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.documentMode < 8)) { + this._historyFrame = document.getElementById('__historyFrame'); + if (!this._historyFrame) throw Error.invalidOperation(Sys.Res.historyMissingFrame); + this._ignoreIFrame = true; + } + if (this._isSafari2()) { + var historyElement = document.getElementById('__history'); + if (!historyElement) throw Error.invalidOperation(Sys.Res.historyMissingHiddenInput); + this._setHistory([window.location.hash]); + this._historyInitialLength = window.history.length; + } + + this._timerHandler = Function.createDelegate(this, this._onIdle); + this._timerCookie = window.setTimeout(this._timerHandler, 100); + + try { + this._initialState = this._deserializeState(this.get_stateString()); + } catch(e) {} + + this._historyInitialized = true; + } + } + function Sys$_Application$_getHistory() { + var historyElement = document.getElementById('__history'); + if (!historyElement) return ''; + var v = historyElement.value; + return v ? Sys.Serialization.JavaScriptSerializer.deserialize(v, true) : ''; + } + function Sys$_Application$_isSafari2() { + return (Sys.Browser.agent === Sys.Browser.Safari) && + (Sys.Browser.version <= 419.3); + } + function Sys$_Application$_loadHandler() { + if(this._loadHandlerDelegate) { + Sys.UI.DomEvent.removeHandler(window, "load", this._loadHandlerDelegate); + this._loadHandlerDelegate = null; + } + this.initialize(); + } + function Sys$_Application$_navigate(entry) { + this._ensureHistory(); + var state = this._deserializeState(entry); + + if (this._uniqueId) { + var oldServerEntry = this._state.__s || ''; + var newServerEntry = state.__s || ''; + if (newServerEntry !== oldServerEntry) { + this._updateHiddenField(newServerEntry); + __doPostBack(this._uniqueId, newServerEntry); + this._state = state; + return; + } + } + this._setState(entry); + this._state = state; + this._raiseNavigate(); + } + function Sys$_Application$_onIdle() { + delete this._timerCookie; + + var entry = this.get_stateString(); + if (entry !== this._currentEntry) { + if (!this._ignoreTimer) { + this._historyPointIsNew = false; + this._navigate(entry); + this._historyLength = window.history.length; + } + } + else { + this._ignoreTimer = false; + } + this._timerCookie = window.setTimeout(this._timerHandler, 100); + } + function Sys$_Application$_onIFrameLoad(entry) { + this._ensureHistory(); + if (!this._ignoreIFrame) { + this._historyPointIsNew = false; + this._navigate(entry); + } + this._ignoreIFrame = false; + } + function Sys$_Application$_onPageRequestManagerBeginRequest(sender, args) { + this._ignoreTimer = true; + } + function Sys$_Application$_onPageRequestManagerEndRequest(sender, args) { + var dataItem = args.get_dataItems()[this._clientId]; + var eventTarget = document.getElementById("__EVENTTARGET"); + if (eventTarget && eventTarget.value === this._uniqueId) { + eventTarget.value = ''; + } + if (typeof(dataItem) !== 'undefined') { + this.setServerState(dataItem); + this._historyPointIsNew = true; + } + else { + this._ignoreTimer = false; + } + var entry = this._serializeState(this._state); + if (entry !== this._currentEntry) { + this._ignoreTimer = true; + this._setState(entry); + this._raiseNavigate(); + } + } + function Sys$_Application$_raiseNavigate() { + var h = this.get_events().getHandler("navigate"); + var stateClone = {}; + for (var key in this._state) { + if (key !== '__s') { + stateClone[key] = this._state[key]; + } + } + var args = new Sys.HistoryEventArgs(stateClone); + if (h) { + h(this, args); + } + } + function Sys$_Application$_serializeState(state) { + var serialized = []; + for (var key in state) { + var value = state[key]; + if (key === '__s') { + var serverState = value; + } + else { + if (key.indexOf('=') !== -1) throw Error.argument('state', Sys.Res.stateFieldNameInvalid); + serialized[serialized.length] = key + '=' + encodeURIComponent(value); + } + } + return serialized.join('&') + (serverState ? '&&' + serverState : ''); + } + function Sys$_Application$_setHistory(historyArray) { + var historyElement = document.getElementById('__history'); + if (historyElement) { + historyElement.value = Sys.Serialization.JavaScriptSerializer.serialize(historyArray); + } + } + function Sys$_Application$_setState(entry, title) { + entry = entry || ''; + if (entry !== this._currentEntry) { + if (window.theForm) { + var action = window.theForm.action; + var hashIndex = action.indexOf('#'); + window.theForm.action = ((hashIndex !== -1) ? action.substring(0, hashIndex) : action) + '#' + entry; + } + + if (this._historyFrame && this._historyPointIsNew) { + this._ignoreIFrame = true; + this._historyPointIsNew = false; + var frameDoc = this._historyFrame.contentWindow.document; + frameDoc.open("javascript:''"); + frameDoc.write("" + (title || document.title) + + "parent.Sys.Application._onIFrameLoad('" + + entry + "');"); + frameDoc.close(); + } + this._ignoreTimer = false; + var currentHash = this.get_stateString(); + this._currentEntry = entry; + if (entry !== currentHash) { + var loc = document.location; + if (loc.href.length - loc.hash.length + entry.length > 1024) { + throw Error.invalidOperation(Sys.Res.urlMustBeLessThan1024chars); + } + if (this._isSafari2()) { + var history = this._getHistory(); + history[window.history.length - this._historyInitialLength + 1] = entry; + this._setHistory(history); + this._historyLength = window.history.length + 1; + var form = document.createElement('form'); + form.method = 'get'; + form.action = '#' + entry; + document.appendChild(form); + form.submit(); + document.removeChild(form); + } + else { + window.location.hash = entry; + } + if ((typeof(title) !== 'undefined') && (title !== null)) { + document.title = title; + } + } + } + } + function Sys$_Application$_unloadHandler(event) { + this.dispose(); + } + function Sys$_Application$_updateHiddenField(value) { + if (this._clientId) { + var serverStateField = document.getElementById(this._clientId); + if (serverStateField) { + serverStateField.value = value; + } + } + } +Sys._Application.prototype = { + _creatingComponents: false, + _disposing: false, + get_isCreatingComponents: Sys$_Application$get_isCreatingComponents, + get_stateString: Sys$_Application$get_stateString, + get_enableHistory: Sys$_Application$get_enableHistory, + set_enableHistory: Sys$_Application$set_enableHistory, + add_init: Sys$_Application$add_init, + remove_init: Sys$_Application$remove_init, + add_load: Sys$_Application$add_load, + remove_load: Sys$_Application$remove_load, + add_navigate: Sys$_Application$add_navigate, + remove_navigate: Sys$_Application$remove_navigate, + add_unload: Sys$_Application$add_unload, + remove_unload: Sys$_Application$remove_unload, + addComponent: Sys$_Application$addComponent, + addHistoryPoint: Sys$_Application$addHistoryPoint, + beginCreateComponents: Sys$_Application$beginCreateComponents, + dispose: Sys$_Application$dispose, + endCreateComponents: Sys$_Application$endCreateComponents, + findComponent: Sys$_Application$findComponent, + getComponents: Sys$_Application$getComponents, + initialize: Sys$_Application$initialize, + notifyScriptLoaded: Sys$_Application$notifyScriptLoaded, + registerDisposableObject: Sys$_Application$registerDisposableObject, + raiseLoad: Sys$_Application$raiseLoad, + removeComponent: Sys$_Application$removeComponent, + setServerId: Sys$_Application$setServerId, + setServerState: Sys$_Application$setServerState, + unregisterDisposableObject: Sys$_Application$unregisterDisposableObject, + _addComponentToSecondPass: Sys$_Application$_addComponentToSecondPass, + _deserializeState: Sys$_Application$_deserializeState, + _doInitialize: Sys$_Application$_doInitialize, + _enableHistoryInScriptManager: Sys$_Application$_enableHistoryInScriptManager, + _ensureHistory: Sys$_Application$_ensureHistory, + _getHistory: Sys$_Application$_getHistory, + _isSafari2: Sys$_Application$_isSafari2, + _loadHandler: Sys$_Application$_loadHandler, + _navigate: Sys$_Application$_navigate, + _onIdle: Sys$_Application$_onIdle, + _onIFrameLoad: Sys$_Application$_onIFrameLoad, + _onPageRequestManagerBeginRequest: Sys$_Application$_onPageRequestManagerBeginRequest, + _onPageRequestManagerEndRequest: Sys$_Application$_onPageRequestManagerEndRequest, + _raiseNavigate: Sys$_Application$_raiseNavigate, + _serializeState: Sys$_Application$_serializeState, + _setHistory: Sys$_Application$_setHistory, + _setState: Sys$_Application$_setState, + _unloadHandler: Sys$_Application$_unloadHandler, + _updateHiddenField: Sys$_Application$_updateHiddenField +} +Sys._Application.registerClass('Sys._Application', Sys.Component, Sys.IContainer); +Sys.Application = new Sys._Application(); +var $find = Sys.Application.findComponent; +Type.registerNamespace('Sys.Net'); + +Sys.Net.WebRequestExecutor = function Sys$Net$WebRequestExecutor() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._webRequest = null; + this._resultObject = null; +} + function Sys$Net$WebRequestExecutor$get_webRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._webRequest; + } + function Sys$Net$WebRequestExecutor$_set_webRequest(value) { + if (this.get_started()) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'set_webRequest')); + } + this._webRequest = value; + } + function Sys$Net$WebRequestExecutor$get_started() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_responseAvailable() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_timedOut() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_aborted() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_responseData() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_statusCode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_statusText() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_xml() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_object() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._resultObject) { + this._resultObject = Sys.Serialization.JavaScriptSerializer.deserialize(this.get_responseData()); + } + return this._resultObject; + } + function Sys$Net$WebRequestExecutor$executeRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$abort() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$getResponseHeader(header) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "header", type: String} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$getAllResponseHeaders() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } +Sys.Net.WebRequestExecutor.prototype = { + get_webRequest: Sys$Net$WebRequestExecutor$get_webRequest, + _set_webRequest: Sys$Net$WebRequestExecutor$_set_webRequest, + get_started: Sys$Net$WebRequestExecutor$get_started, + get_responseAvailable: Sys$Net$WebRequestExecutor$get_responseAvailable, + get_timedOut: Sys$Net$WebRequestExecutor$get_timedOut, + get_aborted: Sys$Net$WebRequestExecutor$get_aborted, + get_responseData: Sys$Net$WebRequestExecutor$get_responseData, + get_statusCode: Sys$Net$WebRequestExecutor$get_statusCode, + get_statusText: Sys$Net$WebRequestExecutor$get_statusText, + get_xml: Sys$Net$WebRequestExecutor$get_xml, + get_object: Sys$Net$WebRequestExecutor$get_object, + executeRequest: Sys$Net$WebRequestExecutor$executeRequest, + abort: Sys$Net$WebRequestExecutor$abort, + getResponseHeader: Sys$Net$WebRequestExecutor$getResponseHeader, + getAllResponseHeaders: Sys$Net$WebRequestExecutor$getAllResponseHeaders +} +Sys.Net.WebRequestExecutor.registerClass('Sys.Net.WebRequestExecutor'); + +Sys.Net.XMLDOM = function Sys$Net$XMLDOM(markup) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "markup", type: String} + ]); + if (e) throw e; + if (!window.DOMParser) { + var progIDs = [ 'Msxml2.DOMDocument.3.0', 'Msxml2.DOMDocument' ]; + for (var i = 0, l = progIDs.length; i < l; i++) { + try { + var xmlDOM = new ActiveXObject(progIDs[i]); + xmlDOM.async = false; + xmlDOM.loadXML(markup); + xmlDOM.setProperty('SelectionLanguage', 'XPath'); + return xmlDOM; + } + catch (ex) { + } + } + } + else { + try { + var domParser = new window.DOMParser(); + return domParser.parseFromString(markup, 'text/xml'); + } + catch (ex) { + } + } + return null; +} +Sys.Net.XMLHttpExecutor = function Sys$Net$XMLHttpExecutor() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Net.XMLHttpExecutor.initializeBase(this); + var _this = this; + this._xmlHttpRequest = null; + this._webRequest = null; + this._responseAvailable = false; + this._timedOut = false; + this._timer = null; + this._aborted = false; + this._started = false; + this._onReadyStateChange = (function () { + + if (_this._xmlHttpRequest.readyState === 4 ) { + try { + if (typeof(_this._xmlHttpRequest.status) === "undefined") { + return; + } + } + catch(ex) { + return; + } + + _this._clearTimer(); + _this._responseAvailable = true; + try { + _this._webRequest.completed(Sys.EventArgs.Empty); + } + finally { + if (_this._xmlHttpRequest != null) { + _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; + _this._xmlHttpRequest = null; + } + } + } + }); + this._clearTimer = (function() { + if (_this._timer != null) { + window.clearTimeout(_this._timer); + _this._timer = null; + } + }); + this._onTimeout = (function() { + if (!_this._responseAvailable) { + _this._clearTimer(); + _this._timedOut = true; + _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; + _this._xmlHttpRequest.abort(); + _this._webRequest.completed(Sys.EventArgs.Empty); + _this._xmlHttpRequest = null; + } + }); +} + function Sys$Net$XMLHttpExecutor$get_timedOut() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._timedOut; + } + function Sys$Net$XMLHttpExecutor$get_started() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._started; + } + function Sys$Net$XMLHttpExecutor$get_responseAvailable() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._responseAvailable; + } + function Sys$Net$XMLHttpExecutor$get_aborted() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._aborted; + } + function Sys$Net$XMLHttpExecutor$executeRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._webRequest = this.get_webRequest(); + if (this._started) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'executeRequest')); + } + if (this._webRequest === null) { + throw Error.invalidOperation(Sys.Res.nullWebRequest); + } + var body = this._webRequest.get_body(); + var headers = this._webRequest.get_headers(); + this._xmlHttpRequest = new XMLHttpRequest(); + this._xmlHttpRequest.onreadystatechange = this._onReadyStateChange; + var verb = this._webRequest.get_httpVerb(); + this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), true ); + if (headers) { + for (var header in headers) { + var val = headers[header]; + if (typeof(val) !== "function") + this._xmlHttpRequest.setRequestHeader(header, val); + } + } + if (verb.toLowerCase() === "post") { + if ((headers === null) || !headers['Content-Type']) { + this._xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); + } + if (!body) { + body = ""; + } + } + var timeout = this._webRequest.get_timeout(); + if (timeout > 0) { + this._timer = window.setTimeout(Function.createDelegate(this, this._onTimeout), timeout); + } + this._xmlHttpRequest.send(body); + this._started = true; + } + function Sys$Net$XMLHttpExecutor$getResponseHeader(header) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "header", type: String} + ]); + if (e) throw e; + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'getResponseHeader')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'getResponseHeader')); + } + var result; + try { + result = this._xmlHttpRequest.getResponseHeader(header); + } catch (e) { + } + if (!result) result = ""; + return result; + } + function Sys$Net$XMLHttpExecutor$getAllResponseHeaders() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'getAllResponseHeaders')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'getAllResponseHeaders')); + } + return this._xmlHttpRequest.getAllResponseHeaders(); + } + function Sys$Net$XMLHttpExecutor$get_responseData() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_responseData')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_responseData')); + } + return this._xmlHttpRequest.responseText; + } + function Sys$Net$XMLHttpExecutor$get_statusCode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusCode')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusCode')); + } + var result = 0; + try { + result = this._xmlHttpRequest.status; + } + catch(ex) { + } + return result; + } + function Sys$Net$XMLHttpExecutor$get_statusText() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusText')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusText')); + } + return this._xmlHttpRequest.statusText; + } + function Sys$Net$XMLHttpExecutor$get_xml() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_xml')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_xml')); + } + var xml = this._xmlHttpRequest.responseXML; + if (!xml || !xml.documentElement) { + xml = Sys.Net.XMLDOM(this._xmlHttpRequest.responseText); + if (!xml || !xml.documentElement) + return null; + } + else if (navigator.userAgent.indexOf('MSIE') !== -1) { + xml.setProperty('SelectionLanguage', 'XPath'); + } + if (xml.documentElement.namespaceURI === "http://www.mozilla.org/newlayout/xml/parsererror.xml" && + xml.documentElement.tagName === "parsererror") { + return null; + } + + if (xml.documentElement.firstChild && xml.documentElement.firstChild.tagName === "parsererror") { + return null; + } + + return xml; + } + function Sys$Net$XMLHttpExecutor$abort() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._started) { + throw Error.invalidOperation(Sys.Res.cannotAbortBeforeStart); + } + if (this._aborted || this._responseAvailable || this._timedOut) + return; + this._aborted = true; + this._clearTimer(); + if (this._xmlHttpRequest && !this._responseAvailable) { + this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; + this._xmlHttpRequest.abort(); + + this._xmlHttpRequest = null; + this._webRequest.completed(Sys.EventArgs.Empty); + } + } +Sys.Net.XMLHttpExecutor.prototype = { + get_timedOut: Sys$Net$XMLHttpExecutor$get_timedOut, + get_started: Sys$Net$XMLHttpExecutor$get_started, + get_responseAvailable: Sys$Net$XMLHttpExecutor$get_responseAvailable, + get_aborted: Sys$Net$XMLHttpExecutor$get_aborted, + executeRequest: Sys$Net$XMLHttpExecutor$executeRequest, + getResponseHeader: Sys$Net$XMLHttpExecutor$getResponseHeader, + getAllResponseHeaders: Sys$Net$XMLHttpExecutor$getAllResponseHeaders, + get_responseData: Sys$Net$XMLHttpExecutor$get_responseData, + get_statusCode: Sys$Net$XMLHttpExecutor$get_statusCode, + get_statusText: Sys$Net$XMLHttpExecutor$get_statusText, + get_xml: Sys$Net$XMLHttpExecutor$get_xml, + abort: Sys$Net$XMLHttpExecutor$abort +} +Sys.Net.XMLHttpExecutor.registerClass('Sys.Net.XMLHttpExecutor', Sys.Net.WebRequestExecutor); + +Sys.Net._WebRequestManager = function Sys$Net$_WebRequestManager() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._defaultTimeout = 0; + this._defaultExecutorType = "Sys.Net.XMLHttpExecutor"; +} + function Sys$Net$_WebRequestManager$add_invokingRequest(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().addHandler("invokingRequest", handler); + } + function Sys$Net$_WebRequestManager$remove_invokingRequest(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().removeHandler("invokingRequest", handler); + } + function Sys$Net$_WebRequestManager$add_completedRequest(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().addHandler("completedRequest", handler); + } + function Sys$Net$_WebRequestManager$remove_completedRequest(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().removeHandler("completedRequest", handler); + } + function Sys$Net$_WebRequestManager$_get_eventHandlerList() { + if (!this._events) { + this._events = new Sys.EventHandlerList(); + } + return this._events; + } + function Sys$Net$_WebRequestManager$get_defaultTimeout() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultTimeout; + } + function Sys$Net$_WebRequestManager$set_defaultTimeout(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Number}]); + if (e) throw e; + if (value < 0) { + throw Error.argumentOutOfRange("value", value, Sys.Res.invalidTimeout); + } + this._defaultTimeout = value; + } + function Sys$Net$_WebRequestManager$get_defaultExecutorType() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultExecutorType; + } + function Sys$Net$_WebRequestManager$set_defaultExecutorType(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + this._defaultExecutorType = value; + } + function Sys$Net$_WebRequestManager$executeRequest(webRequest) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "webRequest", type: Sys.Net.WebRequest} + ]); + if (e) throw e; + var executor = webRequest.get_executor(); + if (!executor) { + var failed = false; + try { + var executorType = eval(this._defaultExecutorType); + executor = new executorType(); + } catch (e) { + failed = true; + } + if (failed || !Sys.Net.WebRequestExecutor.isInstanceOfType(executor) || !executor) { + throw Error.argument("defaultExecutorType", String.format(Sys.Res.invalidExecutorType, this._defaultExecutorType)); + } + webRequest.set_executor(executor); + } + if (executor.get_aborted()) { + return; + } + var evArgs = new Sys.Net.NetworkRequestEventArgs(webRequest); + var handler = this._get_eventHandlerList().getHandler("invokingRequest"); + if (handler) { + handler(this, evArgs); + } + if (!evArgs.get_cancel()) { + executor.executeRequest(); + } + } +Sys.Net._WebRequestManager.prototype = { + add_invokingRequest: Sys$Net$_WebRequestManager$add_invokingRequest, + remove_invokingRequest: Sys$Net$_WebRequestManager$remove_invokingRequest, + add_completedRequest: Sys$Net$_WebRequestManager$add_completedRequest, + remove_completedRequest: Sys$Net$_WebRequestManager$remove_completedRequest, + _get_eventHandlerList: Sys$Net$_WebRequestManager$_get_eventHandlerList, + get_defaultTimeout: Sys$Net$_WebRequestManager$get_defaultTimeout, + set_defaultTimeout: Sys$Net$_WebRequestManager$set_defaultTimeout, + get_defaultExecutorType: Sys$Net$_WebRequestManager$get_defaultExecutorType, + set_defaultExecutorType: Sys$Net$_WebRequestManager$set_defaultExecutorType, + executeRequest: Sys$Net$_WebRequestManager$executeRequest +} +Sys.Net._WebRequestManager.registerClass('Sys.Net._WebRequestManager'); +Sys.Net.WebRequestManager = new Sys.Net._WebRequestManager(); + +Sys.Net.NetworkRequestEventArgs = function Sys$Net$NetworkRequestEventArgs(webRequest) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "webRequest", type: Sys.Net.WebRequest} + ]); + if (e) throw e; + Sys.Net.NetworkRequestEventArgs.initializeBase(this); + this._webRequest = webRequest; +} + function Sys$Net$NetworkRequestEventArgs$get_webRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._webRequest; + } +Sys.Net.NetworkRequestEventArgs.prototype = { + get_webRequest: Sys$Net$NetworkRequestEventArgs$get_webRequest +} +Sys.Net.NetworkRequestEventArgs.registerClass('Sys.Net.NetworkRequestEventArgs', Sys.CancelEventArgs); + +Sys.Net.WebRequest = function Sys$Net$WebRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._url = ""; + this._headers = { }; + this._body = null; + this._userContext = null; + this._httpVerb = null; + this._executor = null; + this._invokeCalled = false; + this._timeout = 0; +} + function Sys$Net$WebRequest$add_completed(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().addHandler("completed", handler); + } + function Sys$Net$WebRequest$remove_completed(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().removeHandler("completed", handler); + } + function Sys$Net$WebRequest$completed(eventArgs) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "eventArgs", type: Sys.EventArgs} + ]); + if (e) throw e; + var handler = Sys.Net.WebRequestManager._get_eventHandlerList().getHandler("completedRequest"); + if (handler) { + handler(this._executor, eventArgs); + } + handler = this._get_eventHandlerList().getHandler("completed"); + if (handler) { + handler(this._executor, eventArgs); + } + } + function Sys$Net$WebRequest$_get_eventHandlerList() { + if (!this._events) { + this._events = new Sys.EventHandlerList(); + } + return this._events; + } + function Sys$Net$WebRequest$get_url() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._url; + } + function Sys$Net$WebRequest$set_url(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + this._url = value; + } + function Sys$Net$WebRequest$get_headers() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._headers; + } + function Sys$Net$WebRequest$get_httpVerb() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._httpVerb === null) { + if (this._body === null) { + return "GET"; + } + return "POST"; + } + return this._httpVerb; + } + function Sys$Net$WebRequest$set_httpVerb(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + if (value.length === 0) { + throw Error.argument('value', Sys.Res.invalidHttpVerb); + } + this._httpVerb = value; + } + function Sys$Net$WebRequest$get_body() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._body; + } + function Sys$Net$WebRequest$set_body(value) { + var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); + if (e) throw e; + this._body = value; + } + function Sys$Net$WebRequest$get_userContext() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._userContext; + } + function Sys$Net$WebRequest$set_userContext(value) { + var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); + if (e) throw e; + this._userContext = value; + } + function Sys$Net$WebRequest$get_executor() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._executor; + } + function Sys$Net$WebRequest$set_executor(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Sys.Net.WebRequestExecutor}]); + if (e) throw e; + if (this._executor !== null && this._executor.get_started()) { + throw Error.invalidOperation(Sys.Res.setExecutorAfterActive); + } + this._executor = value; + this._executor._set_webRequest(this); + } + function Sys$Net$WebRequest$get_timeout() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._timeout === 0) { + return Sys.Net.WebRequestManager.get_defaultTimeout(); + } + return this._timeout; + } + function Sys$Net$WebRequest$set_timeout(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Number}]); + if (e) throw e; + if (value < 0) { + throw Error.argumentOutOfRange("value", value, Sys.Res.invalidTimeout); + } + this._timeout = value; + } + function Sys$Net$WebRequest$getResolvedUrl() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return Sys.Net.WebRequest._resolveUrl(this._url); + } + function Sys$Net$WebRequest$invoke() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._invokeCalled) { + throw Error.invalidOperation(Sys.Res.invokeCalledTwice); + } + Sys.Net.WebRequestManager.executeRequest(this); + this._invokeCalled = true; + } +Sys.Net.WebRequest.prototype = { + add_completed: Sys$Net$WebRequest$add_completed, + remove_completed: Sys$Net$WebRequest$remove_completed, + completed: Sys$Net$WebRequest$completed, + _get_eventHandlerList: Sys$Net$WebRequest$_get_eventHandlerList, + get_url: Sys$Net$WebRequest$get_url, + set_url: Sys$Net$WebRequest$set_url, + get_headers: Sys$Net$WebRequest$get_headers, + get_httpVerb: Sys$Net$WebRequest$get_httpVerb, + set_httpVerb: Sys$Net$WebRequest$set_httpVerb, + get_body: Sys$Net$WebRequest$get_body, + set_body: Sys$Net$WebRequest$set_body, + get_userContext: Sys$Net$WebRequest$get_userContext, + set_userContext: Sys$Net$WebRequest$set_userContext, + get_executor: Sys$Net$WebRequest$get_executor, + set_executor: Sys$Net$WebRequest$set_executor, + get_timeout: Sys$Net$WebRequest$get_timeout, + set_timeout: Sys$Net$WebRequest$set_timeout, + getResolvedUrl: Sys$Net$WebRequest$getResolvedUrl, + invoke: Sys$Net$WebRequest$invoke +} +Sys.Net.WebRequest._resolveUrl = function Sys$Net$WebRequest$_resolveUrl(url, baseUrl) { + if (url && url.indexOf('://') !== -1) { + return url; + } + if (!baseUrl || baseUrl.length === 0) { + var baseElement = document.getElementsByTagName('base')[0]; + if (baseElement && baseElement.href && baseElement.href.length > 0) { + baseUrl = baseElement.href; + } + else { + baseUrl = document.URL; + } + } + var qsStart = baseUrl.indexOf('?'); + if (qsStart !== -1) { + baseUrl = baseUrl.substr(0, qsStart); + } + qsStart = baseUrl.indexOf('#'); + if (qsStart !== -1) { + baseUrl = baseUrl.substr(0, qsStart); + } + baseUrl = baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1); + if (!url || url.length === 0) { + return baseUrl; + } + if (url.charAt(0) === '/') { + var slashslash = baseUrl.indexOf('://'); + if (slashslash === -1) { + throw Error.argument("baseUrl", Sys.Res.badBaseUrl1); + } + var nextSlash = baseUrl.indexOf('/', slashslash + 3); + if (nextSlash === -1) { + throw Error.argument("baseUrl", Sys.Res.badBaseUrl2); + } + return baseUrl.substr(0, nextSlash) + url; + } + else { + var lastSlash = baseUrl.lastIndexOf('/'); + if (lastSlash === -1) { + throw Error.argument("baseUrl", Sys.Res.badBaseUrl3); + } + return baseUrl.substr(0, lastSlash+1) + url; + } +} +Sys.Net.WebRequest._createQueryString = function Sys$Net$WebRequest$_createQueryString(queryString, encodeMethod) { + if (!encodeMethod) + encodeMethod = encodeURIComponent; + var sb = new Sys.StringBuilder(); + var i = 0; + for (var arg in queryString) { + var obj = queryString[arg]; + if (typeof(obj) === "function") continue; + var val = Sys.Serialization.JavaScriptSerializer.serialize(obj); + if (i !== 0) { + sb.append('&'); + } + sb.append(arg); + sb.append('='); + sb.append(encodeMethod(val)); + i++; + } + return sb.toString(); +} +Sys.Net.WebRequest._createUrl = function Sys$Net$WebRequest$_createUrl(url, queryString) { + if (!queryString) { + return url; + } + var qs = Sys.Net.WebRequest._createQueryString(queryString); + if (qs.length > 0) { + var sep = '?'; + if (url && url.indexOf('?') !== -1) + sep = '&'; + return url + sep + qs; + } else { + return url; + } +} +Sys.Net.WebRequest.registerClass('Sys.Net.WebRequest'); + +Sys.Net.WebServiceProxy = function Sys$Net$WebServiceProxy() { +} + function Sys$Net$WebServiceProxy$get_timeout() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._timeout; + } + function Sys$Net$WebServiceProxy$set_timeout(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Number}]); + if (e) throw e; + if (value < 0) { throw Error.argumentOutOfRange('value', value, Sys.Res.invalidTimeout); } + this._timeout = value; + } + function Sys$Net$WebServiceProxy$get_defaultUserContext() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._userContext; + } + function Sys$Net$WebServiceProxy$set_defaultUserContext(value) { + var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); + if (e) throw e; + this._userContext = value; + } + function Sys$Net$WebServiceProxy$get_defaultSucceededCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._succeeded; + } + function Sys$Net$WebServiceProxy$set_defaultSucceededCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._succeeded = value; + } + function Sys$Net$WebServiceProxy$get_defaultFailedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._failed; + } + function Sys$Net$WebServiceProxy$set_defaultFailedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._failed = value; + } + function Sys$Net$WebServiceProxy$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path; + } + function Sys$Net$WebServiceProxy$set_path(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + this._path = value; + } + function Sys$Net$WebServiceProxy$_invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "servicePath", type: String}, + {name: "methodName", type: String}, + {name: "useGet", type: Boolean}, + {name: "params"}, + {name: "onSuccess", type: Function, mayBeNull: true, optional: true}, + {name: "onFailure", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (onSuccess === null || typeof onSuccess === 'undefined') onSuccess = this.get_defaultSucceededCallback(); + if (onFailure === null || typeof onFailure === 'undefined') onFailure = this.get_defaultFailedCallback(); + if (userContext === null || typeof userContext === 'undefined') userContext = this.get_defaultUserContext(); + + return Sys.Net.WebServiceProxy.invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext, this.get_timeout()); + } +Sys.Net.WebServiceProxy.prototype = { + get_timeout: Sys$Net$WebServiceProxy$get_timeout, + set_timeout: Sys$Net$WebServiceProxy$set_timeout, + get_defaultUserContext: Sys$Net$WebServiceProxy$get_defaultUserContext, + set_defaultUserContext: Sys$Net$WebServiceProxy$set_defaultUserContext, + get_defaultSucceededCallback: Sys$Net$WebServiceProxy$get_defaultSucceededCallback, + set_defaultSucceededCallback: Sys$Net$WebServiceProxy$set_defaultSucceededCallback, + get_defaultFailedCallback: Sys$Net$WebServiceProxy$get_defaultFailedCallback, + set_defaultFailedCallback: Sys$Net$WebServiceProxy$set_defaultFailedCallback, + get_path: Sys$Net$WebServiceProxy$get_path, + set_path: Sys$Net$WebServiceProxy$set_path, + _invoke: Sys$Net$WebServiceProxy$_invoke +} +Sys.Net.WebServiceProxy.registerClass('Sys.Net.WebServiceProxy'); +Sys.Net.WebServiceProxy.invoke = function Sys$Net$WebServiceProxy$invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext, timeout) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "servicePath", type: String}, + {name: "methodName", type: String}, + {name: "useGet", type: Boolean, optional: true}, + {name: "params", mayBeNull: true, optional: true}, + {name: "onSuccess", type: Function, mayBeNull: true, optional: true}, + {name: "onFailure", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true}, + {name: "timeout", type: Number, optional: true} + ]); + if (e) throw e; + var request = new Sys.Net.WebRequest(); + request.get_headers()['Content-Type'] = 'application/json; charset=utf-8'; + if (!params) params = {}; + var urlParams = params; + if (!useGet || !urlParams) urlParams = {}; + request.set_url(Sys.Net.WebRequest._createUrl(servicePath+"/"+encodeURIComponent(methodName), urlParams)); + var body = null; + if (!useGet) { + body = Sys.Serialization.JavaScriptSerializer.serialize(params); + if (body === "{}") body = ""; + } + request.set_body(body); + request.add_completed(onComplete); + if (timeout && timeout > 0) request.set_timeout(timeout); + request.invoke(); + function onComplete(response, eventArgs) { + if (response.get_responseAvailable()) { + var statusCode = response.get_statusCode(); + var result = null; + + try { + var contentType = response.getResponseHeader("Content-Type"); + if (contentType.startsWith("application/json")) { + result = response.get_object(); + } + else if (contentType.startsWith("text/xml")) { + result = response.get_xml(); + } + else { + result = response.get_responseData(); + } + } catch (ex) { + } + var error = response.getResponseHeader("jsonerror"); + var errorObj = (error === "true"); + if (errorObj) { + if (result) { + result = new Sys.Net.WebServiceError(false, result.Message, result.StackTrace, result.ExceptionType); + } + } + else if (contentType.startsWith("application/json")) { + if (!result || typeof(result.d) === "undefined") { + throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceInvalidJsonWrapper, methodName)); + } + result = result.d; + } + if (((statusCode < 200) || (statusCode >= 300)) || errorObj) { + if (onFailure) { + if (!result || !errorObj) { + result = new Sys.Net.WebServiceError(false , String.format(Sys.Res.webServiceFailedNoMsg, methodName), "", ""); + } + result._statusCode = statusCode; + onFailure(result, userContext, methodName); + } + else { + var error; + if (result && errorObj) { + error = result.get_exceptionType() + "-- " + result.get_message(); + } + else { + error = response.get_responseData(); + } + throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); + } + } + else if (onSuccess) { + onSuccess(result, userContext, methodName); + } + } + else { + var msg; + if (response.get_timedOut()) { + msg = String.format(Sys.Res.webServiceTimedOut, methodName); + } + else { + msg = String.format(Sys.Res.webServiceFailedNoMsg, methodName) + } + if (onFailure) { + onFailure(new Sys.Net.WebServiceError(response.get_timedOut(), msg, "", ""), userContext, methodName); + } + else { + throw Sys.Net.WebServiceProxy._createFailedError(methodName, msg); + } + } + } + return request; +} +Sys.Net.WebServiceProxy._createFailedError = function Sys$Net$WebServiceProxy$_createFailedError(methodName, errorMessage) { + var displayMessage = "Sys.Net.WebServiceFailedException: " + errorMessage; + var e = Error.create(displayMessage, { 'name': 'Sys.Net.WebServiceFailedException', 'methodName': methodName }); + e.popStackFrame(); + return e; +} +Sys.Net.WebServiceProxy._defaultFailedCallback = function Sys$Net$WebServiceProxy$_defaultFailedCallback(err, methodName) { + var error = err.get_exceptionType() + "-- " + err.get_message(); + throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); +} +Sys.Net.WebServiceProxy._generateTypedConstructor = function Sys$Net$WebServiceProxy$_generateTypedConstructor(type) { + return function(properties) { + if (properties) { + for (var name in properties) { + this[name] = properties[name]; + } + } + this.__type = type; + } +} + +Sys.Net.WebServiceError = function Sys$Net$WebServiceError(timedOut, message, stackTrace, exceptionType) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "timedOut", type: Boolean}, + {name: "message", type: String, mayBeNull: true}, + {name: "stackTrace", type: String, mayBeNull: true}, + {name: "exceptionType", type: String, mayBeNull: true} + ]); + if (e) throw e; + this._timedOut = timedOut; + this._message = message; + this._stackTrace = stackTrace; + this._exceptionType = exceptionType; + this._statusCode = -1; +} + function Sys$Net$WebServiceError$get_timedOut() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._timedOut; + } + function Sys$Net$WebServiceError$get_statusCode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._statusCode; + } + function Sys$Net$WebServiceError$get_message() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._message; + } + function Sys$Net$WebServiceError$get_stackTrace() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._stackTrace; + } + function Sys$Net$WebServiceError$get_exceptionType() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._exceptionType; + } +Sys.Net.WebServiceError.prototype = { + get_timedOut: Sys$Net$WebServiceError$get_timedOut, + get_statusCode: Sys$Net$WebServiceError$get_statusCode, + get_message: Sys$Net$WebServiceError$get_message, + get_stackTrace: Sys$Net$WebServiceError$get_stackTrace, + get_exceptionType: Sys$Net$WebServiceError$get_exceptionType +} +Sys.Net.WebServiceError.registerClass('Sys.Net.WebServiceError'); +Type.registerNamespace('Sys.Services'); +Sys.Services._ProfileService = function Sys$Services$_ProfileService() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Services._ProfileService.initializeBase(this); + this.properties = {}; +} +Sys.Services._ProfileService.DefaultWebServicePath = ''; + function Sys$Services$_ProfileService$get_defaultLoadCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLoadCompletedCallback; + } + function Sys$Services$_ProfileService$set_defaultLoadCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLoadCompletedCallback = value; + } + function Sys$Services$_ProfileService$get_defaultSaveCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultSaveCompletedCallback; + } + function Sys$Services$_ProfileService$set_defaultSaveCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultSaveCompletedCallback = value; + } + function Sys$Services$_ProfileService$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path || ''; + } + function Sys$Services$_ProfileService$load(propertyNames, loadCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyNames", type: Array, mayBeNull: true, optional: true, elementType: String}, + {name: "loadCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var parameters; + var methodName; + if (!propertyNames) { + methodName = "GetAllPropertiesForCurrentUser"; + parameters = { authenticatedUserOnly: false }; + } + else { + methodName = "GetPropertiesForCurrentUser"; + parameters = { properties: this._clonePropertyNames(propertyNames), authenticatedUserOnly: false }; + } + this._invoke(this._get_path(), + methodName, + false, + parameters, + Function.createDelegate(this, this._onLoadComplete), + Function.createDelegate(this, this._onLoadFailed), + [loadCompletedCallback, failedCallback, userContext]); + } + function Sys$Services$_ProfileService$save(propertyNames, saveCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyNames", type: Array, mayBeNull: true, optional: true, elementType: String}, + {name: "saveCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var flattenedProperties = this._flattenProperties(propertyNames, this.properties); + this._invoke(this._get_path(), + "SetPropertiesForCurrentUser", + false, + { values: flattenedProperties.value, authenticatedUserOnly: false }, + Function.createDelegate(this, this._onSaveComplete), + Function.createDelegate(this, this._onSaveFailed), + [saveCompletedCallback, failedCallback, userContext, flattenedProperties.count]); + } + function Sys$Services$_ProfileService$_clonePropertyNames(arr) { + var nodups = []; + var seen = {}; + for (var i=0; i < arr.length; i++) { + var prop = arr[i]; + if(!seen[prop]) { Array.add(nodups, prop); seen[prop]=true; }; + } + return nodups; + } + function Sys$Services$_ProfileService$_flattenProperties(propertyNames, properties, groupName) { + var flattenedProperties = {}; + var val; + var key; + var count = 0; + if (propertyNames && propertyNames.length === 0) { + return { value: flattenedProperties, count: 0 }; + } + for (var property in properties) { + val = properties[property]; + key = groupName ? groupName + "." + property : property; + if(Sys.Services.ProfileGroup.isInstanceOfType(val)) { + var obj = this._flattenProperties(propertyNames, val, key); + var groupProperties = obj.value; + count += obj.count; + for(var subKey in groupProperties) { + var subVal = groupProperties[subKey]; + flattenedProperties[subKey] = subVal; + } + } + else { + if(!propertyNames || Array.indexOf(propertyNames, key) !== -1) { + flattenedProperties[key] = val; + count++; + } + } + } + return { value: flattenedProperties, count: count }; + } + function Sys$Services$_ProfileService$_get_path() { + var path = this.get_path(); + if (!path.length) { + path = Sys.Services._ProfileService.DefaultWebServicePath; + } + if (!path || !path.length) { + throw Error.invalidOperation(Sys.Res.servicePathNotSet); + } + return path; + } + function Sys$Services$_ProfileService$_onLoadComplete(result, context, methodName) { + if (typeof(result) !== "object") { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Object")); + } + var unflattened = this._unflattenProperties(result); + for (var name in unflattened) { + this.properties[name] = unflattened[name]; + } + + var callback = context[0] || this.get_defaultLoadCompletedCallback() || this.get_defaultSucceededCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(result.length, userContext, "Sys.Services.ProfileService.load"); + } + } + function Sys$Services$_ProfileService$_onLoadFailed(err, context, methodName) { + var callback = context[1] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.ProfileService.load"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_ProfileService$_onSaveComplete(result, context, methodName) { + var count = context[3]; + if (result !== null) { + if (result instanceof Array) { + count -= result.length; + } + else if (typeof(result) === 'number') { + count = result; + } + else { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Array")); + } + } + + var callback = context[0] || this.get_defaultSaveCompletedCallback() || this.get_defaultSucceededCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(count, userContext, "Sys.Services.ProfileService.save"); + } + } + function Sys$Services$_ProfileService$_onSaveFailed(err, context, methodName) { + var callback = context[1] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.ProfileService.save"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_ProfileService$_unflattenProperties(properties) { + var unflattenedProperties = {}; + var dotIndex; + var val; + var count = 0; + for (var key in properties) { + count++; + val = properties[key]; + dotIndex = key.indexOf('.'); + if (dotIndex !== -1) { + var groupName = key.substr(0, dotIndex); + key = key.substr(dotIndex+1); + var group = unflattenedProperties[groupName]; + if (!group || !Sys.Services.ProfileGroup.isInstanceOfType(group)) { + group = new Sys.Services.ProfileGroup(); + unflattenedProperties[groupName] = group; + } + group[key] = val; + } + else { + unflattenedProperties[key] = val; + } + } + properties.length = count; + return unflattenedProperties; + } +Sys.Services._ProfileService.prototype = { + _defaultLoadCompletedCallback: null, + _defaultSaveCompletedCallback: null, + _path: '', + _timeout: 0, + get_defaultLoadCompletedCallback: Sys$Services$_ProfileService$get_defaultLoadCompletedCallback, + set_defaultLoadCompletedCallback: Sys$Services$_ProfileService$set_defaultLoadCompletedCallback, + get_defaultSaveCompletedCallback: Sys$Services$_ProfileService$get_defaultSaveCompletedCallback, + set_defaultSaveCompletedCallback: Sys$Services$_ProfileService$set_defaultSaveCompletedCallback, + get_path: Sys$Services$_ProfileService$get_path, + load: Sys$Services$_ProfileService$load, + save: Sys$Services$_ProfileService$save, + _clonePropertyNames: Sys$Services$_ProfileService$_clonePropertyNames, + _flattenProperties: Sys$Services$_ProfileService$_flattenProperties, + _get_path: Sys$Services$_ProfileService$_get_path, + _onLoadComplete: Sys$Services$_ProfileService$_onLoadComplete, + _onLoadFailed: Sys$Services$_ProfileService$_onLoadFailed, + _onSaveComplete: Sys$Services$_ProfileService$_onSaveComplete, + _onSaveFailed: Sys$Services$_ProfileService$_onSaveFailed, + _unflattenProperties: Sys$Services$_ProfileService$_unflattenProperties +} +Sys.Services._ProfileService.registerClass('Sys.Services._ProfileService', Sys.Net.WebServiceProxy); +Sys.Services.ProfileService = new Sys.Services._ProfileService(); +Sys.Services.ProfileGroup = function Sys$Services$ProfileGroup(properties) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "properties", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (properties) { + for (var property in properties) { + this[property] = properties[property]; + } + } +} +Sys.Services.ProfileGroup.registerClass('Sys.Services.ProfileGroup'); +Sys.Services._AuthenticationService = function Sys$Services$_AuthenticationService() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Services._AuthenticationService.initializeBase(this); +} +Sys.Services._AuthenticationService.DefaultWebServicePath = ''; + function Sys$Services$_AuthenticationService$get_defaultLoginCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLoginCompletedCallback; + } + function Sys$Services$_AuthenticationService$set_defaultLoginCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLoginCompletedCallback = value; + } + function Sys$Services$_AuthenticationService$get_defaultLogoutCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLogoutCompletedCallback; + } + function Sys$Services$_AuthenticationService$set_defaultLogoutCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLogoutCompletedCallback = value; + } + function Sys$Services$_AuthenticationService$get_isLoggedIn() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._authenticated; + } + function Sys$Services$_AuthenticationService$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path || ''; + } + function Sys$Services$_AuthenticationService$login(username, password, isPersistent, customInfo, redirectUrl, loginCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "username", type: String}, + {name: "password", type: String, mayBeNull: true}, + {name: "isPersistent", type: Boolean, mayBeNull: true, optional: true}, + {name: "customInfo", type: String, mayBeNull: true, optional: true}, + {name: "redirectUrl", type: String, mayBeNull: true, optional: true}, + {name: "loginCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._invoke(this._get_path(), "Login", false, + { userName: username, password: password, createPersistentCookie: isPersistent }, + Function.createDelegate(this, this._onLoginComplete), + Function.createDelegate(this, this._onLoginFailed), + [username, password, isPersistent, customInfo, redirectUrl, loginCompletedCallback, failedCallback, userContext]); + } + function Sys$Services$_AuthenticationService$logout(redirectUrl, logoutCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "redirectUrl", type: String, mayBeNull: true, optional: true}, + {name: "logoutCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._invoke(this._get_path(), "Logout", false, {}, + Function.createDelegate(this, this._onLogoutComplete), + Function.createDelegate(this, this._onLogoutFailed), + [redirectUrl, logoutCompletedCallback, failedCallback, userContext]); + } + function Sys$Services$_AuthenticationService$_get_path() { + var path = this.get_path(); + if(!path.length) { + path = Sys.Services._AuthenticationService.DefaultWebServicePath; + } + if(!path || !path.length) { + throw Error.invalidOperation(Sys.Res.servicePathNotSet); + } + return path; + } + function Sys$Services$_AuthenticationService$_onLoginComplete(result, context, methodName) { + if(typeof(result) !== "boolean") { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Boolean")); + } + + var redirectUrl = context[4]; + var userContext = context[7] || this.get_defaultUserContext(); + var callback = context[5] || this.get_defaultLoginCompletedCallback() || this.get_defaultSucceededCallback(); + + if(result) { + this._authenticated = true; + if (callback) { + callback(true, userContext, "Sys.Services.AuthenticationService.login"); + } + + if (typeof(redirectUrl) !== "undefined" && redirectUrl !== null) { + window.location.href = redirectUrl; + } + } + else if (callback) { + callback(false, userContext, "Sys.Services.AuthenticationService.login"); + } + } + function Sys$Services$_AuthenticationService$_onLoginFailed(err, context, methodName) { + var callback = context[6] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[7] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.AuthenticationService.login"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_AuthenticationService$_onLogoutComplete(result, context, methodName) { + if(result !== null) { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "null")); + } + + var redirectUrl = context[0]; + var userContext = context[3] || this.get_defaultUserContext(); + var callback = context[1] || this.get_defaultLogoutCompletedCallback() || this.get_defaultSucceededCallback(); + this._authenticated = false; + + if (callback) { + callback(null, userContext, "Sys.Services.AuthenticationService.logout"); + } + + if(!redirectUrl) { + window.location.reload(); + } + else { + window.location.href = redirectUrl; + } + } + function Sys$Services$_AuthenticationService$_onLogoutFailed(err, context, methodName) { + var callback = context[2] || this.get_defaultFailedCallback(); + if (callback) { + callback(err, context[3], "Sys.Services.AuthenticationService.logout"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_AuthenticationService$_setAuthenticated(authenticated) { + this._authenticated = authenticated; + } +Sys.Services._AuthenticationService.prototype = { + _defaultLoginCompletedCallback: null, + _defaultLogoutCompletedCallback: null, + _path: '', + _timeout: 0, + _authenticated: false, + get_defaultLoginCompletedCallback: Sys$Services$_AuthenticationService$get_defaultLoginCompletedCallback, + set_defaultLoginCompletedCallback: Sys$Services$_AuthenticationService$set_defaultLoginCompletedCallback, + get_defaultLogoutCompletedCallback: Sys$Services$_AuthenticationService$get_defaultLogoutCompletedCallback, + set_defaultLogoutCompletedCallback: Sys$Services$_AuthenticationService$set_defaultLogoutCompletedCallback, + get_isLoggedIn: Sys$Services$_AuthenticationService$get_isLoggedIn, + get_path: Sys$Services$_AuthenticationService$get_path, + login: Sys$Services$_AuthenticationService$login, + logout: Sys$Services$_AuthenticationService$logout, + _get_path: Sys$Services$_AuthenticationService$_get_path, + _onLoginComplete: Sys$Services$_AuthenticationService$_onLoginComplete, + _onLoginFailed: Sys$Services$_AuthenticationService$_onLoginFailed, + _onLogoutComplete: Sys$Services$_AuthenticationService$_onLogoutComplete, + _onLogoutFailed: Sys$Services$_AuthenticationService$_onLogoutFailed, + _setAuthenticated: Sys$Services$_AuthenticationService$_setAuthenticated +} +Sys.Services._AuthenticationService.registerClass('Sys.Services._AuthenticationService', Sys.Net.WebServiceProxy); +Sys.Services.AuthenticationService = new Sys.Services._AuthenticationService(); +Sys.Services._RoleService = function Sys$Services$_RoleService() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Services._RoleService.initializeBase(this); + this._roles = []; +} +Sys.Services._RoleService.DefaultWebServicePath = ''; + function Sys$Services$_RoleService$get_defaultLoadCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLoadCompletedCallback; + } + function Sys$Services$_RoleService$set_defaultLoadCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLoadCompletedCallback = value; + } + function Sys$Services$_RoleService$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path || ''; + } + function Sys$Services$_RoleService$get_roles() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return Array.clone(this._roles); + } + function Sys$Services$_RoleService$isUserInRole(role) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "role", type: String} + ]); + if (e) throw e; + var v = this._get_rolesIndex()[role.trim().toLowerCase()]; + return !!v; + } + function Sys$Services$_RoleService$load(loadCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "loadCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + Sys.Net.WebServiceProxy.invoke( + this._get_path(), + "GetRolesForCurrentUser", + false, + {} , + Function.createDelegate(this, this._onLoadComplete), + Function.createDelegate(this, this._onLoadFailed), + [loadCompletedCallback, failedCallback, userContext], + this.get_timeout()); + } + function Sys$Services$_RoleService$_get_path() { + var path = this.get_path(); + if(!path || !path.length) { + path = Sys.Services._RoleService.DefaultWebServicePath; + } + if(!path || !path.length) { + throw Error.invalidOperation(Sys.Res.servicePathNotSet); + } + return path; + } + function Sys$Services$_RoleService$_get_rolesIndex() { + if (!this._rolesIndex) { + var index = {}; + for(var i=0; i < this._roles.length; i++) { + index[this._roles[i].toLowerCase()] = true; + } + this._rolesIndex = index; + } + return this._rolesIndex; + } + function Sys$Services$_RoleService$_onLoadComplete(result, context, methodName) { + if(result && !(result instanceof Array)) { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Array")); + } + this._roles = result; + this._rolesIndex = null; + var callback = context[0] || this.get_defaultLoadCompletedCallback() || this.get_defaultSucceededCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + var clonedResult = Array.clone(result); + callback(clonedResult, userContext, "Sys.Services.RoleService.load"); + } + } + function Sys$Services$_RoleService$_onLoadFailed(err, context, methodName) { + var callback = context[1] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.RoleService.load"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } +Sys.Services._RoleService.prototype = { + _defaultLoadCompletedCallback: null, + _rolesIndex: null, + _timeout: 0, + _path: '', + get_defaultLoadCompletedCallback: Sys$Services$_RoleService$get_defaultLoadCompletedCallback, + set_defaultLoadCompletedCallback: Sys$Services$_RoleService$set_defaultLoadCompletedCallback, + get_path: Sys$Services$_RoleService$get_path, + get_roles: Sys$Services$_RoleService$get_roles, + isUserInRole: Sys$Services$_RoleService$isUserInRole, + load: Sys$Services$_RoleService$load, + _get_path: Sys$Services$_RoleService$_get_path, + _get_rolesIndex: Sys$Services$_RoleService$_get_rolesIndex, + _onLoadComplete: Sys$Services$_RoleService$_onLoadComplete, + _onLoadFailed: Sys$Services$_RoleService$_onLoadFailed +} +Sys.Services._RoleService.registerClass('Sys.Services._RoleService', Sys.Net.WebServiceProxy); +Sys.Services.RoleService = new Sys.Services._RoleService(); +Type.registerNamespace('Sys.Serialization'); +Sys.Serialization.JavaScriptSerializer = function Sys$Serialization$JavaScriptSerializer() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} +Sys.Serialization.JavaScriptSerializer.registerClass('Sys.Serialization.JavaScriptSerializer'); +Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs = []; +Sys.Serialization.JavaScriptSerializer._charsToEscape = []; +Sys.Serialization.JavaScriptSerializer._dateRegEx = new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\\"', 'g'); +Sys.Serialization.JavaScriptSerializer._escapeChars = {}; +Sys.Serialization.JavaScriptSerializer._escapeRegEx = new RegExp('["\\\\\\x00-\\x1F]', 'i'); +Sys.Serialization.JavaScriptSerializer._escapeRegExGlobal = new RegExp('["\\\\\\x00-\\x1F]', 'g'); +Sys.Serialization.JavaScriptSerializer._jsonRegEx = new RegExp('[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]', 'g'); +Sys.Serialization.JavaScriptSerializer._jsonStringRegEx = new RegExp('"(\\\\.|[^"\\\\])*"', 'g'); +Sys.Serialization.JavaScriptSerializer._serverTypeFieldName = '__type'; +Sys.Serialization.JavaScriptSerializer._init = function Sys$Serialization$JavaScriptSerializer$_init() { + var replaceChars = ['\\u0000','\\u0001','\\u0002','\\u0003','\\u0004','\\u0005','\\u0006','\\u0007', + '\\b','\\t','\\n','\\u000b','\\f','\\r','\\u000e','\\u000f','\\u0010','\\u0011', + '\\u0012','\\u0013','\\u0014','\\u0015','\\u0016','\\u0017','\\u0018','\\u0019', + '\\u001a','\\u001b','\\u001c','\\u001d','\\u001e','\\u001f']; + Sys.Serialization.JavaScriptSerializer._charsToEscape[0] = '\\'; + Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs['\\'] = new RegExp('\\\\', 'g'); + Sys.Serialization.JavaScriptSerializer._escapeChars['\\'] = '\\\\'; + Sys.Serialization.JavaScriptSerializer._charsToEscape[1] = '"'; + Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs['"'] = new RegExp('"', 'g'); + Sys.Serialization.JavaScriptSerializer._escapeChars['"'] = '\\"'; + for (var i = 0; i < 32; i++) { + var c = String.fromCharCode(i); + Sys.Serialization.JavaScriptSerializer._charsToEscape[i+2] = c; + Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs[c] = new RegExp(c, 'g'); + Sys.Serialization.JavaScriptSerializer._escapeChars[c] = replaceChars[i]; + } +} +Sys.Serialization.JavaScriptSerializer._serializeBooleanWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeBooleanWithBuilder(object, stringBuilder) { + stringBuilder.append(object.toString()); +} +Sys.Serialization.JavaScriptSerializer._serializeNumberWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeNumberWithBuilder(object, stringBuilder) { + if (isFinite(object)) { + stringBuilder.append(String(object)); + } + else { + throw Error.invalidOperation(Sys.Res.cannotSerializeNonFiniteNumbers); + } +} +Sys.Serialization.JavaScriptSerializer._serializeStringWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeStringWithBuilder(string, stringBuilder) { + stringBuilder.append('"'); + if (Sys.Serialization.JavaScriptSerializer._escapeRegEx.test(string)) { + if (Sys.Serialization.JavaScriptSerializer._charsToEscape.length === 0) { + Sys.Serialization.JavaScriptSerializer._init(); + } + if (string.length < 128) { + string = string.replace(Sys.Serialization.JavaScriptSerializer._escapeRegExGlobal, + function(x) { return Sys.Serialization.JavaScriptSerializer._escapeChars[x]; }); + } + else { + for (var i = 0; i < 34; i++) { + var c = Sys.Serialization.JavaScriptSerializer._charsToEscape[i]; + if (string.indexOf(c) !== -1) { + if (Sys.Browser.agent === Sys.Browser.Opera || Sys.Browser.agent === Sys.Browser.FireFox) { + string = string.split(c).join(Sys.Serialization.JavaScriptSerializer._escapeChars[c]); + } + else { + string = string.replace(Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs[c], + Sys.Serialization.JavaScriptSerializer._escapeChars[c]); + } + } + } + } + } + stringBuilder.append(string); + stringBuilder.append('"'); +} +Sys.Serialization.JavaScriptSerializer._serializeWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeWithBuilder(object, stringBuilder, sort, prevObjects) { + var i; + switch (typeof object) { + case 'object': + if (object) { + if (prevObjects){ + for( var j = 0; j < prevObjects.length; j++) { + if (prevObjects[j] === object) { + throw Error.invalidOperation(Sys.Res.cannotSerializeObjectWithCycle); + } + } + } + else { + prevObjects = new Array(); + } + try { + Array.add(prevObjects, object); + + if (Number.isInstanceOfType(object)){ + Sys.Serialization.JavaScriptSerializer._serializeNumberWithBuilder(object, stringBuilder); + } + else if (Boolean.isInstanceOfType(object)){ + Sys.Serialization.JavaScriptSerializer._serializeBooleanWithBuilder(object, stringBuilder); + } + else if (String.isInstanceOfType(object)){ + Sys.Serialization.JavaScriptSerializer._serializeStringWithBuilder(object, stringBuilder); + } + + else if (Array.isInstanceOfType(object)) { + stringBuilder.append('['); + + for (i = 0; i < object.length; ++i) { + if (i > 0) { + stringBuilder.append(','); + } + Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(object[i], stringBuilder,false,prevObjects); + } + stringBuilder.append(']'); + } + else { + if (Date.isInstanceOfType(object)) { + stringBuilder.append('"\\/Date('); + stringBuilder.append(object.getTime()); + stringBuilder.append(')\\/"'); + break; + } + var properties = []; + var propertyCount = 0; + for (var name in object) { + if (name.startsWith('$')) { + continue; + } + if (name === Sys.Serialization.JavaScriptSerializer._serverTypeFieldName && propertyCount !== 0){ + properties[propertyCount++] = properties[0]; + properties[0] = name; + } + else{ + properties[propertyCount++] = name; + } + } + if (sort) properties.sort(); + stringBuilder.append('{'); + var needComma = false; + + for (i=0; i + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", mayBeNull: true} + ]); + if (e) throw e; + var stringBuilder = new Sys.StringBuilder(); + Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(object, stringBuilder, false); + return stringBuilder.toString(); +} +Sys.Serialization.JavaScriptSerializer.deserialize = function Sys$Serialization$JavaScriptSerializer$deserialize(data, secure) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "data", type: String}, + {name: "secure", type: Boolean, optional: true} + ]); + if (e) throw e; + + if (data.length === 0) throw Error.argument('data', Sys.Res.cannotDeserializeEmptyString); + try { + var exp = data.replace(Sys.Serialization.JavaScriptSerializer._dateRegEx, "$1new Date($2)"); + + if (secure && Sys.Serialization.JavaScriptSerializer._jsonRegEx.test( + exp.replace(Sys.Serialization.JavaScriptSerializer._jsonStringRegEx, ''))) throw null; + return eval('(' + exp + ')'); + } + catch (e) { + throw Error.argument('data', Sys.Res.cannotDeserializeInvalidJson); + } +} + +Sys.CultureInfo = function Sys$CultureInfo(name, numberFormat, dateTimeFormat) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "name", type: String}, + {name: "numberFormat", type: Object}, + {name: "dateTimeFormat", type: Object} + ]); + if (e) throw e; + this.name = name; + this.numberFormat = numberFormat; + this.dateTimeFormat = dateTimeFormat; +} + function Sys$CultureInfo$_getDateTimeFormats() { + if (! this._dateTimeFormats) { + var dtf = this.dateTimeFormat; + this._dateTimeFormats = + [ dtf.MonthDayPattern, + dtf.YearMonthPattern, + dtf.ShortDatePattern, + dtf.ShortTimePattern, + dtf.LongDatePattern, + dtf.LongTimePattern, + dtf.FullDateTimePattern, + dtf.RFC1123Pattern, + dtf.SortableDateTimePattern, + dtf.UniversalSortableDateTimePattern ]; + } + return this._dateTimeFormats; + } + function Sys$CultureInfo$_getMonthIndex(value) { + if (!this._upperMonths) { + this._upperMonths = this._toUpperArray(this.dateTimeFormat.MonthNames); + } + return Array.indexOf(this._upperMonths, this._toUpper(value)); + } + function Sys$CultureInfo$_getAbbrMonthIndex(value) { + if (!this._upperAbbrMonths) { + this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); + } + return Array.indexOf(this._upperAbbrMonths, this._toUpper(value)); + } + function Sys$CultureInfo$_getDayIndex(value) { + if (!this._upperDays) { + this._upperDays = this._toUpperArray(this.dateTimeFormat.DayNames); + } + return Array.indexOf(this._upperDays, this._toUpper(value)); + } + function Sys$CultureInfo$_getAbbrDayIndex(value) { + if (!this._upperAbbrDays) { + this._upperAbbrDays = this._toUpperArray(this.dateTimeFormat.AbbreviatedDayNames); + } + return Array.indexOf(this._upperAbbrDays, this._toUpper(value)); + } + function Sys$CultureInfo$_toUpperArray(arr) { + var result = []; + for (var i = 0, il = arr.length; i < il; i++) { + result[i] = this._toUpper(arr[i]); + } + return result; + } + function Sys$CultureInfo$_toUpper(value) { + return value.split("\u00A0").join(' ').toUpperCase(); + } +Sys.CultureInfo.prototype = { + _getDateTimeFormats: Sys$CultureInfo$_getDateTimeFormats, + _getMonthIndex: Sys$CultureInfo$_getMonthIndex, + _getAbbrMonthIndex: Sys$CultureInfo$_getAbbrMonthIndex, + _getDayIndex: Sys$CultureInfo$_getDayIndex, + _getAbbrDayIndex: Sys$CultureInfo$_getAbbrDayIndex, + _toUpperArray: Sys$CultureInfo$_toUpperArray, + _toUpper: Sys$CultureInfo$_toUpper +} +Sys.CultureInfo._parse = function Sys$CultureInfo$_parse(value) { + var cultureInfo = Sys.Serialization.JavaScriptSerializer.deserialize(value); + return new Sys.CultureInfo(cultureInfo.name, cultureInfo.numberFormat, cultureInfo.dateTimeFormat); +} +Sys.CultureInfo.registerClass('Sys.CultureInfo'); +Sys.CultureInfo.InvariantCulture = Sys.CultureInfo._parse('{"name":"","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"\u00A4","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, dd MMMM yyyy HH:mm:ss","LongDatePattern":"dddd, dd MMMM yyyy","LongTimePattern":"HH:mm:ss","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"MM/dd/yyyy","ShortTimePattern":"HH:mm","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"yyyy MMMM","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]}}'); +if (typeof(__cultureInfo) === 'undefined') { + var __cultureInfo = '{"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":false,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":false},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM dd, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM dd, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"MMMM, yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":false,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]}}'; +} +Sys.CultureInfo.CurrentCulture = Sys.CultureInfo._parse(__cultureInfo); +delete __cultureInfo; + +Sys.UI.Behavior = function Sys$UI$Behavior(element) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + Sys.UI.Behavior.initializeBase(this); + this._element = element; + var behaviors = element._behaviors; + if (!behaviors) { + element._behaviors = [this]; + } + else { + behaviors[behaviors.length] = this; + } +} + function Sys$UI$Behavior$get_element() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._element; + } + function Sys$UI$Behavior$get_id() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var baseId = Sys.UI.Behavior.callBaseMethod(this, 'get_id'); + if (baseId) return baseId; + if (!this._element || !this._element.id) return ''; + return this._element.id + '$' + this.get_name(); + } + function Sys$UI$Behavior$get_name() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._name) return this._name; + var name = Object.getTypeName(this); + var i = name.lastIndexOf('.'); + if (i != -1) name = name.substr(i + 1); + if (!this.get_isInitialized()) this._name = name; + return name; + } + function Sys$UI$Behavior$set_name(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + if ((value === '') || (value.charAt(0) === ' ') || (value.charAt(value.length - 1) === ' ')) + throw Error.argument('value', Sys.Res.invalidId); + if (typeof(this._element[value]) !== 'undefined') + throw Error.invalidOperation(String.format(Sys.Res.behaviorDuplicateName, value)); + if (this.get_isInitialized()) throw Error.invalidOperation(Sys.Res.cantSetNameAfterInit); + this._name = value; + } + function Sys$UI$Behavior$initialize() { + Sys.UI.Behavior.callBaseMethod(this, 'initialize'); + var name = this.get_name(); + if (name) this._element[name] = this; + } + function Sys$UI$Behavior$dispose() { + Sys.UI.Behavior.callBaseMethod(this, 'dispose'); + if (this._element) { + var name = this.get_name(); + if (name) { + this._element[name] = null; + } + Array.remove(this._element._behaviors, this); + delete this._element; + } + } +Sys.UI.Behavior.prototype = { + _name: null, + get_element: Sys$UI$Behavior$get_element, + get_id: Sys$UI$Behavior$get_id, + get_name: Sys$UI$Behavior$get_name, + set_name: Sys$UI$Behavior$set_name, + initialize: Sys$UI$Behavior$initialize, + dispose: Sys$UI$Behavior$dispose +} +Sys.UI.Behavior.registerClass('Sys.UI.Behavior', Sys.Component); +Sys.UI.Behavior.getBehaviorByName = function Sys$UI$Behavior$getBehaviorByName(element, name) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "name", type: String} + ]); + if (e) throw e; + var b = element[name]; + return (b && Sys.UI.Behavior.isInstanceOfType(b)) ? b : null; +} +Sys.UI.Behavior.getBehaviors = function Sys$UI$Behavior$getBehaviors(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if (!element._behaviors) return []; + return Array.clone(element._behaviors); +} +Sys.UI.Behavior.getBehaviorsByType = function Sys$UI$Behavior$getBehaviorsByType(element, type) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "type", type: Type} + ]); + if (e) throw e; + var behaviors = element._behaviors; + var results = []; + if (behaviors) { + for (var i = 0, l = behaviors.length; i < l; i++) { + if (type.isInstanceOfType(behaviors[i])) { + results[results.length] = behaviors[i]; + } + } + } + return results; +} + +Sys.UI.VisibilityMode = function Sys$UI$VisibilityMode() { + /// + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.VisibilityMode.prototype = { + hide: 0, + collapse: 1 +} +Sys.UI.VisibilityMode.registerEnum("Sys.UI.VisibilityMode"); + +Sys.UI.Control = function Sys$UI$Control(element) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if (typeof(element.control) != 'undefined') throw Error.invalidOperation(Sys.Res.controlAlreadyDefined); + Sys.UI.Control.initializeBase(this); + this._element = element; + element.control = this; +} + function Sys$UI$Control$get_element() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._element; + } + function Sys$UI$Control$get_id() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._element) return ''; + return this._element.id; + } + function Sys$UI$Control$set_id(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + throw Error.invalidOperation(Sys.Res.cantSetId); + } + function Sys$UI$Control$get_parent() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._parent) return this._parent; + if (!this._element) return null; + + var parentElement = this._element.parentNode; + while (parentElement) { + if (parentElement.control) { + return parentElement.control; + } + parentElement = parentElement.parentNode; + } + return null; + } + function Sys$UI$Control$set_parent(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Sys.UI.Control}]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + var parents = [this]; + var current = value; + while (current) { + if (Array.contains(parents, current)) throw Error.invalidOperation(Sys.Res.circularParentChain); + parents[parents.length] = current; + current = current.get_parent(); + } + this._parent = value; + } + function Sys$UI$Control$get_visibilityMode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + return Sys.UI.DomElement.getVisibilityMode(this._element); + } + function Sys$UI$Control$set_visibilityMode(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Sys.UI.VisibilityMode}]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.setVisibilityMode(this._element, value); + } + function Sys$UI$Control$get_visible() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + return Sys.UI.DomElement.getVisible(this._element); + } + function Sys$UI$Control$set_visible(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.setVisible(this._element, value) + } + function Sys$UI$Control$addCssClass(className) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "className", type: String} + ]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.addCssClass(this._element, className); + } + function Sys$UI$Control$dispose() { + Sys.UI.Control.callBaseMethod(this, 'dispose'); + if (this._element) { + this._element.control = undefined; + delete this._element; + } + if (this._parent) delete this._parent; + } + function Sys$UI$Control$onBubbleEvent(source, args) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "source"}, + {name: "args", type: Sys.EventArgs} + ]); + if (e) throw e; + return false; + } + function Sys$UI$Control$raiseBubbleEvent(source, args) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "source"}, + {name: "args", type: Sys.EventArgs} + ]); + if (e) throw e; + var currentTarget = this.get_parent(); + while (currentTarget) { + if (currentTarget.onBubbleEvent(source, args)) { + return; + } + currentTarget = currentTarget.get_parent(); + } + } + function Sys$UI$Control$removeCssClass(className) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "className", type: String} + ]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.removeCssClass(this._element, className); + } + function Sys$UI$Control$toggleCssClass(className) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "className", type: String} + ]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.toggleCssClass(this._element, className); + } +Sys.UI.Control.prototype = { + _parent: null, + _visibilityMode: Sys.UI.VisibilityMode.hide, + get_element: Sys$UI$Control$get_element, + get_id: Sys$UI$Control$get_id, + set_id: Sys$UI$Control$set_id, + get_parent: Sys$UI$Control$get_parent, + set_parent: Sys$UI$Control$set_parent, + get_visibilityMode: Sys$UI$Control$get_visibilityMode, + set_visibilityMode: Sys$UI$Control$set_visibilityMode, + get_visible: Sys$UI$Control$get_visible, + set_visible: Sys$UI$Control$set_visible, + addCssClass: Sys$UI$Control$addCssClass, + dispose: Sys$UI$Control$dispose, + onBubbleEvent: Sys$UI$Control$onBubbleEvent, + raiseBubbleEvent: Sys$UI$Control$raiseBubbleEvent, + removeCssClass: Sys$UI$Control$removeCssClass, + toggleCssClass: Sys$UI$Control$toggleCssClass +} +Sys.UI.Control.registerClass('Sys.UI.Control', Sys.Component); + + +Type.registerNamespace('Sys'); + +Sys.Res={ +'urlMustBeLessThan1024chars':'The history state must be small enough to not make the url larger than 1024 characters.', +'argumentTypeName':'Value is not the name of an existing type.', +'methodRegisteredTwice':'Method {0} has already been registered.', +'cantSetIdAfterInit':'The id property can\'t be set on this object after initialization.', +'cantBeCalledAfterDispose':'Can\'t be called after dispose.', +'componentCantSetIdAfterAddedToApp':'The id property of a component can\'t be set after it\'s been added to the Application object.', +'behaviorDuplicateName':'A behavior with name \'{0}\' already exists or it is the name of an existing property on the target element.', +'notATypeName':'Value is not a valid type name.', +'typeShouldBeTypeOrString':'Value is not a valid type or a valid type name.', +'historyInvalidHistorySettingCombination':'Cannot set enableHistory to false when ScriptManager.EnableHistory is true.', +'stateMustBeStringDictionary':'The state object can only have null and string fields.', +'boolTrueOrFalse':'Value must be \'true\' or \'false\'.', +'scriptLoadFailedNoHead':'ScriptLoader requires pages to contain a element.', +'stringFormatInvalid':'The format string is invalid.', +'referenceNotFound':'Component \'{0}\' was not found.', +'enumReservedName':'\'{0}\' is a reserved name that can\'t be used as an enum value name.', +'eventHandlerNotFound':'Handler not found.', +'circularParentChain':'The chain of control parents can\'t have circular references.', +'undefinedEvent':'\'{0}\' is not an event.', +'notAMethod':'{0} is not a method.', +'propertyUndefined':'\'{0}\' is not a property or an existing field.', +'historyCannotEnableHistory':'Cannot set enableHistory after initialization.', +'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.', +'scriptLoadFailedDebug':'The script \'{0}\' failed to load. Check for:\r\n Inaccessible path.\r\n Script errors. (IE) Enable \'Display a notification about every script error\' under advanced settings.\r\n Missing call to Sys.Application.notifyScriptLoaded().', +'propertyNotWritable':'\'{0}\' is not a writable property.', +'enumInvalidValueName':'\'{0}\' is not a valid name for an enum value.', +'controlAlreadyDefined':'A control is already associated with the element.', +'addHandlerCantBeUsedForError':'Can\'t add a handler for the error event using this method. Please set the window.onerror property instead.', +'namespaceContainsObject':'Object {0} already exists and is not a namespace.', +'cantAddNonFunctionhandler':'Can\'t add a handler that is not a function.', +'invalidNameSpace':'Value is not a valid namespace identifier.', +'notAnInterface':'Value is not a valid interface.', +'eventHandlerNotFunction':'Handler must be a function.', +'propertyNotAnArray':'\'{0}\' is not an Array property.', +'typeRegisteredTwice':'Type {0} has already been registered. The type may be defined multiple times or the script file that defines it may have already been loaded. A possible cause is a change of settings during a partial update.', +'cantSetNameAfterInit':'The name property can\'t be set on this object after initialization.', +'historyMissingFrame':'For the history feature to work in IE, the page must have an iFrame element with id \'__historyFrame\' pointed to a page that gets its title from the \'title\' query string parameter and calls Sys.Application._onIFrameLoad() on the parent window. This can be done by setting EnableHistory to true on ScriptManager.', +'appDuplicateComponent':'Two components with the same id \'{0}\' can\'t be added to the application.', +'historyCannotAddHistoryPointWithHistoryDisabled':'A history point can only be added if enableHistory is set to true.', +'appComponentMustBeInitialized':'Components must be initialized before they are added to the Application object.', +'baseNotAClass':'Value is not a class.', +'methodNotFound':'No method found with name \'{0}\'.', +'arrayParseBadFormat':'Value must be a valid string representation for an array. It must start with a \'[\' and end with a \']\'.', +'stateFieldNameInvalid':'State field names must not contain any \'=\' characters.', +'cantSetId':'The id property can\'t be set on this object.', +'historyMissingHiddenInput':'For the history feature to work in Safari 2, the page must have a hidden input element with id \'__history\'.', +'stringFormatBraceMismatch':'The format string contains an unmatched opening or closing brace.', +'enumValueNotInteger':'An enumeration definition can only contain integer values.', +'propertyNullOrUndefined':'Cannot set the properties of \'{0}\' because it returned a null value.', +'argumentDomNode':'Value must be a DOM element or a text node.', +'componentCantSetIdTwice':'The id property of a component can\'t be set more than once.', +'createComponentOnDom':'Value must be null for Components that are not Controls or Behaviors.', +'createNotComponent':'{0} does not derive from Sys.Component.', +'createNoDom':'Value must not be null for Controls and Behaviors.', +'cantAddWithoutId':'Can\'t add a component that doesn\'t have an id.', +'badTypeName':'Value is not the name of the type being registered or the name is a reserved word.', +'argumentInteger':'Value must be an integer.', +'scriptLoadMultipleCallbacks':'The script \'{0}\' contains multiple calls to Sys.Application.notifyScriptLoaded(). Only one is allowed.', +'invokeCalledTwice':'Cannot call invoke more than once.', +'webServiceFailed':'The server method \'{0}\' failed with the following error: {1}', +'webServiceInvalidJsonWrapper':'The server method \'{0}\' returned invalid data. The \'d\' property is missing from the JSON wrapper.', +'argumentType':'Object cannot be converted to the required type.', +'argumentNull':'Value cannot be null.', +'controlCantSetId':'The id property can\'t be set on a control.', +'formatBadFormatSpecifier':'Format specifier was invalid.', +'webServiceFailedNoMsg':'The server method \'{0}\' failed.', +'argumentDomElement':'Value must be a DOM element.', +'invalidExecutorType':'Could not create a valid Sys.Net.WebRequestExecutor from: {0}.', +'cannotCallBeforeResponse':'Cannot call {0} when responseAvailable is false.', +'actualValue':'Actual value was {0}.', +'enumInvalidValue':'\'{0}\' is not a valid value for enum {1}.', +'scriptLoadFailed':'The script \'{0}\' could not be loaded.', +'parameterCount':'Parameter count mismatch.', +'cannotDeserializeEmptyString':'Cannot deserialize empty string.', +'formatInvalidString':'Input string was not in a correct format.', +'invalidTimeout':'Value must be greater than or equal to zero.', +'cannotAbortBeforeStart':'Cannot abort when executor has not started.', +'argument':'Value does not fall within the expected range.', +'cannotDeserializeInvalidJson':'Cannot deserialize. The data does not correspond to valid JSON.', +'invalidHttpVerb':'httpVerb cannot be set to an empty or null string.', +'nullWebRequest':'Cannot call executeRequest with a null webRequest.', +'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.', +'cannotSerializeNonFiniteNumbers':'Cannot serialize non finite numbers.', +'argumentUndefined':'Value cannot be undefined.', +'webServiceInvalidReturnType':'The server method \'{0}\' returned an invalid type. Expected type: {1}', +'servicePathNotSet':'The path to the web service has not been set.', +'argumentTypeWithTypes':'Object of type \'{0}\' cannot be converted to type \'{1}\'.', +'cannotCallOnceStarted':'Cannot call {0} once started.', +'badBaseUrl1':'Base URL does not contain ://.', +'badBaseUrl2':'Base URL does not contain another /.', +'badBaseUrl3':'Cannot find last / in base URL.', +'setExecutorAfterActive':'Cannot set executor after it has become active.', +'paramName':'Parameter name: {0}', +'cannotCallOutsideHandler':'Cannot call {0} outside of a completed event handler.', +'cannotSerializeObjectWithCycle':'Cannot serialize object with cyclic reference within child properties.', +'format':'One of the identified items was in an invalid format.', +'assertFailedCaller':'Assertion Failed: {0}\r\nat {1}', +'argumentOutOfRange':'Specified argument was out of the range of valid values.', +'webServiceTimedOut':'The server method \'{0}\' timed out.', +'notImplemented':'The method or operation is not implemented.', +'assertFailed':'Assertion Failed: {0}', +'invalidOperation':'Operation is not valid due to the current state of the object.', +'breakIntoDebugger':'{0}\r\n\r\nBreak into debugger?' +}; + +if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded(); diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/MicrosoftAjax.js b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/MicrosoftAjax.js new file mode 100644 index 00000000..db85c14e --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/MicrosoftAjax.js @@ -0,0 +1,7 @@ +//---------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All rights reserved. +//---------------------------------------------------------- +// MicrosoftAjax.js +Function.__typeName="Function";Function.__class=true;Function.createCallback=function(b,a){return function(){var e=arguments.length;if(e>0){var d=[];for(var c=0;cc){var f=Error.parameterCount();f.popStackFrame();return f}return null};Function._validateParameter=function(c,a,h){var b,g=a.type,l=!!a.integer,k=!!a.domElement,m=!!a.mayBeNull;b=Function._validateParameterType(c,g,l,k,m,h);if(b){b.popStackFrame();return b}var e=a.elementType,f=!!a.elementMayBeNull;if(g===Array&&typeof c!=="undefined"&&c!==null&&(e||!f)){var j=!!a.elementInteger,i=!!a.elementDomElement;for(var d=0;d0&&(dc.Calendar.TwoDigitYearMax)return a-100}return a};Date._getParseRegExp=function(b,e){if(!b._parseRegExp)b._parseRegExp={};else if(b._parseRegExp[e])return b._parseRegExp[e];var c=Date._expandFormat(b,e);c=c.replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g,"\\\\$1");var a=new Sys.StringBuilder("^"),j=[],f=0,i=0,h=Date._getTokenRegExp(),d;while((d=h.exec(c))!==null){var l=c.slice(f,d.index);f=h.lastIndex;i+=Date._appendPreOrPostMatch(l,a);if(i%2===1){a.append(d[0]);continue}switch(d[0]){case "dddd":case "ddd":case "MMMM":case "MMM":a.append("(\\D+)");break;case "tt":case "t":a.append("(\\D*)");break;case "yyyy":a.append("(\\d{4})");break;case "fff":a.append("(\\d{3})");break;case "ff":a.append("(\\d{2})");break;case "f":a.append("(\\d)");break;case "dd":case "d":case "MM":case "M":case "yy":case "y":case "HH":case "H":case "hh":case "h":case "mm":case "m":case "ss":case "s":a.append("(\\d\\d?)");break;case "zzz":a.append("([+-]?\\d\\d?:\\d{2})");break;case "zz":case "z":a.append("([+-]?\\d\\d?)")}Array.add(j,d[0])}Date._appendPreOrPostMatch(c.slice(f),a);a.append("$");var k=a.toString().replace(/\s+/g,"\\s+"),g={"regExp":k,"groups":j};b._parseRegExp[e]=g;return g};Date._getTokenRegExp=function(){return /dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g};Date.parseLocale=function(a){return Date._parse(a,Sys.CultureInfo.CurrentCulture,arguments)};Date.parseInvariant=function(a){return Date._parse(a,Sys.CultureInfo.InvariantCulture,arguments)};Date._parse=function(g,c,h){var e=false;for(var a=1,i=h.length;a31)return null;break;case "MMMM":c=j._getMonthIndex(a);if(c<0||c>11)return null;break;case "MMM":c=j._getAbbrMonthIndex(a);if(c<0||c>11)return null;break;case "M":case "MM":var c=parseInt(a,10)-1;if(c<0||c>11)return null;break;case "y":case "yy":f=Date._expandYear(m,parseInt(a,10));if(f<0||f>9999)return null;break;case "yyyy":f=parseInt(a,10);if(f<0||f>9999)return null;break;case "h":case "hh":d=parseInt(a,10);if(d===12)d=0;if(d<0||d>11)return null;break;case "H":case "HH":d=parseInt(a,10);if(d<0||d>23)return null;break;case "m":case "mm":n=parseInt(a,10);if(n<0||n>59)return null;break;case "s":case "ss":o=parseInt(a,10);if(o<0||o>59)return null;break;case "tt":case "t":var u=a.toUpperCase();r=u===m.PMDesignator.toUpperCase();if(!r&&u!==m.AMDesignator.toUpperCase())return null;break;case "f":e=parseInt(a,10)*100;if(e<0||e>999)return null;break;case "ff":e=parseInt(a,10)*10;if(e<0||e>999)return null;break;case "fff":e=parseInt(a,10);if(e<0||e>999)return null;break;case "dddd":g=j._getDayIndex(a);if(g<0||g>6)return null;break;case "ddd":g=j._getAbbrDayIndex(a);if(g<0||g>6)return null;break;case "zzz":var q=a.split(/:/);if(q.length!==2)return null;var i=parseInt(q[0],10);if(i<-12||i>13)return null;var l=parseInt(q[1],10);if(l<0||l>59)return null;k=i*60+(a.startsWith("-")?-l:l);break;case "z":case "zz":var i=parseInt(a,10);if(i<-12||i>13)return null;k=i*60}}var b=new Date;if(f===null)f=b.getFullYear();if(c===null)c=b.getMonth();if(h===null)h=b.getDate();b.setFullYear(f,c,h);if(b.getDate()!==h)return null;if(g!==null&&b.getDay()!==g)return null;if(r&&d<12)d+=12;b.setHours(d,n,o,e);if(k!==null){var t=b.getMinutes()-(k+b.getTimezoneOffset());b.setHours(b.getHours()+parseInt(t/60,10),t%60)}return b};Date.prototype.format=function(a){return this._toFormattedString(a,Sys.CultureInfo.InvariantCulture)};Date.prototype.localeFormat=function(a){return this._toFormattedString(a,Sys.CultureInfo.CurrentCulture)};Date.prototype._toFormattedString=function(e,h){if(!e||e.length===0||e==="i")if(h&&h.name.length>0)return this.toLocaleString();else return this.toString();var d=h.dateTimeFormat;e=Date._expandFormat(d,e);var a=new Sys.StringBuilder,b;function c(a){if(a<10)return "0"+a;return a.toString()}function g(a){if(a<10)return "00"+a;if(a<100)return "0"+a;return a.toString()}var j=0,i=Date._getTokenRegExp();for(;true;){var l=i.lastIndex,f=i.exec(e),k=e.slice(l,f?f.index:e.length);j+=Date._appendPreOrPostMatch(k,a);if(!f)break;if(j%2===1){a.append(f[0]);continue}switch(f[0]){case "dddd":a.append(d.DayNames[this.getDay()]);break;case "ddd":a.append(d.AbbreviatedDayNames[this.getDay()]);break;case "dd":a.append(c(this.getDate()));break;case "d":a.append(this.getDate());break;case "MMMM":a.append(d.MonthNames[this.getMonth()]);break;case "MMM":a.append(d.AbbreviatedMonthNames[this.getMonth()]);break;case "MM":a.append(c(this.getMonth()+1));break;case "M":a.append(this.getMonth()+1);break;case "yyyy":a.append(this.getFullYear());break;case "yy":a.append(c(this.getFullYear()%100));break;case "y":a.append(this.getFullYear()%100);break;case "hh":b=this.getHours()%12;if(b===0)b=12;a.append(c(b));break;case "h":b=this.getHours()%12;if(b===0)b=12;a.append(b);break;case "HH":a.append(c(this.getHours()));break;case "H":a.append(this.getHours());break;case "mm":a.append(c(this.getMinutes()));break;case "m":a.append(this.getMinutes());break;case "ss":a.append(c(this.getSeconds()));break;case "s":a.append(this.getSeconds());break;case "tt":a.append(this.getHours()<12?d.AMDesignator:d.PMDesignator);break;case "t":a.append((this.getHours()<12?d.AMDesignator:d.PMDesignator).charAt(0));break;case "f":a.append(g(this.getMilliseconds()).charAt(0));break;case "ff":a.append(g(this.getMilliseconds()).substr(0,2));break;case "fff":a.append(g(this.getMilliseconds()));break;case "z":b=this.getTimezoneOffset()/60;a.append((b<=0?"+":"-")+Math.floor(Math.abs(b)));break;case "zz":b=this.getTimezoneOffset()/60;a.append((b<=0?"+":"-")+c(Math.floor(Math.abs(b))));break;case "zzz":b=this.getTimezoneOffset()/60;a.append((b<=0?"+":"-")+c(Math.floor(Math.abs(b)))+d.TimeSeparator+c(Math.abs(this.getTimezoneOffset()%60)))}}return a.toString()};Number.__typeName="Number";Number.__class=true;Number.parseLocale=function(a){return Number._parse(a,Sys.CultureInfo.CurrentCulture)};Number.parseInvariant=function(a){return Number._parse(a,Sys.CultureInfo.InvariantCulture)};Number._parse=function(b,o){b=b.trim();if(b.match(/^[+-]?infinity$/i))return parseFloat(b);if(b.match(/^0x[a-f0-9]+$/i))return parseInt(b);var a=o.numberFormat,g=Number._parseNumberNegativePattern(b,a,a.NumberNegativePattern),h=g[0],e=g[1];if(h===""&&a.NumberNegativePattern!==1){g=Number._parseNumberNegativePattern(b,a,1);h=g[0];e=g[1]}if(h==="")h="+";var j,d,f=e.indexOf("e");if(f<0)f=e.indexOf("E");if(f<0){d=e;j=null}else{d=e.substr(0,f);j=e.substr(f+1)}var c,k,m=d.indexOf(a.NumberDecimalSeparator);if(m<0){c=d;k=null}else{c=d.substr(0,m);k=d.substr(m+a.NumberDecimalSeparator.length)}c=c.split(a.NumberGroupSeparator).join("");var n=a.NumberGroupSeparator.replace(/\u00A0/g," ");if(a.NumberGroupSeparator!==n)c=c.split(n).join("");var l=h+c;if(k!==null)l+="."+k;if(j!==null){var i=Number._parseNumberNegativePattern(j,a,1);if(i[0]==="")i[0]="+";l+="e"+i[0]+i[1]}if(l.match(/^[+-]?\d*\.?\d*(e[+-]?\d+)?$/))return parseFloat(l);return Number.NaN};Number._parseNumberNegativePattern=function(a,d,e){var b=d.NegativeSign,c=d.PositiveSign;switch(e){case 4:b=" "+b;c=" "+c;case 3:if(a.endsWith(b))return ["-",a.substr(0,a.length-b.length)];else if(a.endsWith(c))return ["+",a.substr(0,a.length-c.length)];break;case 2:b+=" ";c+=" ";case 1:if(a.startsWith(b))return ["-",a.substr(b.length)];else if(a.startsWith(c))return ["+",a.substr(c.length)];break;case 0:if(a.startsWith("(")&&a.endsWith(")"))return ["-",a.substr(1,a.length-2)]}return ["",a]};Number.prototype.format=function(a){return this._toFormattedString(a,Sys.CultureInfo.InvariantCulture)};Number.prototype.localeFormat=function(a){return this._toFormattedString(a,Sys.CultureInfo.CurrentCulture)};Number.prototype._toFormattedString=function(d,j){if(!d||d.length===0||d==="i")if(j&&j.name.length>0)return this.toLocaleString();else return this.toString();var o=["n %","n%","%n"],n=["-n %","-n%","-%n"],p=["(n)","-n","- n","n-","n -"],m=["$n","n$","$ n","n $"],l=["($n)","-$n","$-n","$n-","(n$)","-n$","n-$","n$-","-n $","-$ n","n $-","$ n-","$ -n","n- $","($ n)","(n $)"];function g(a,c,d){for(var b=a.length;b1?parseInt(e[1]):0;e=b.split(".");b=e[0];a=e.length>1?e[1]:"";var q;if(c>0){a=g(a,c,false);b+=a.slice(0,c);a=a.substr(c)}else if(c<0){c=-c;b=g(b,c+1,true);a=b.slice(-c,b.length)+a;b=b.slice(0,-c)}if(i>0){if(a.length>i)a=a.slice(0,i);else a=g(a,i,false);a=p+a}else a="";var d=b.length-1,f="";while(d>=0){if(h===0||h>d)if(f.length>0)return b.slice(0,d+1)+n+f+a;else return b.slice(0,d+1)+a;if(f.length>0)f=b.slice(d-h+1,d+1)+n+f;else f=b.slice(d-h+1,d+1);d-=h;if(k1)b=parseInt(d.slice(1),10);var c;switch(d.charAt(0)){case "d":case "D":c="n";if(b!==-1)e=g(""+e,b,true);if(this<0)e=-e;break;case "c":case "C":if(this<0)c=l[a.CurrencyNegativePattern];else c=m[a.CurrencyPositivePattern];if(b===-1)b=a.CurrencyDecimalDigits;e=i(Math.abs(this),b,a.CurrencyGroupSizes,a.CurrencyGroupSeparator,a.CurrencyDecimalSeparator);break;case "n":case "N":if(this<0)c=p[a.NumberNegativePattern];else c="n";if(b===-1)b=a.NumberDecimalDigits;e=i(Math.abs(this),b,a.NumberGroupSizes,a.NumberGroupSeparator,a.NumberDecimalSeparator);break;case "p":case "P":if(this<0)c=n[a.PercentNegativePattern];else c=o[a.PercentPositivePattern];if(b===-1)b=a.PercentDecimalDigits;e=i(Math.abs(this)*100,b,a.PercentGroupSizes,a.PercentGroupSeparator,a.PercentDecimalSeparator);break;default:throw Error.format(Sys.Res.formatBadFormatSpecifier)}var k=/n|\$|-|%/g,f="";for(;true;){var q=k.lastIndex,h=k.exec(c);f+=c.slice(q,h?h.index:c.length);if(!h)break;switch(h[0]){case "n":f+=e;break;case "$":f+=a.CurrencySymbol;break;case "-":f+=a.NegativeSign;break;case "%":f+=a.PercentSymbol}}return f};RegExp.__typeName="RegExp";RegExp.__class=true;Array.__typeName="Array";Array.__class=true;Array.add=Array.enqueue=function(a,b){a[a.length]=b};Array.addRange=function(a,b){a.push.apply(a,b)};Array.clear=function(a){a.length=0};Array.clone=function(a){if(a.length===1)return [a[0]];else return Array.apply(null,a)};Array.contains=function(a,b){return Array.indexOf(a,b)>=0};Array.dequeue=function(a){return a.shift()};Array.forEach=function(b,e,d){for(var a=0,f=b.length;a=0)b.splice(a,1);return a>=0};Array.removeAt=function(a,b){a.splice(b,1)};if(!window)this.window=this;window.Type=Function;Type.prototype.callBaseMethod=function(a,d,b){var c=this.getBaseMethod(a,d);if(!b)return c.apply(a);else return c.apply(a,b)};Type.prototype.getBaseMethod=function(d,c){var b=this.getBaseType();if(b){var a=b.prototype[c];return a instanceof Function?a:null}return null};Type.prototype.getBaseType=function(){return typeof this.__baseType==="undefined"?null:this.__baseType};Type.prototype.getInterfaces=function(){var a=[],b=this;while(b){var c=b.__interfaces;if(c)for(var d=0,f=c.length;d-1){Sys.Browser.agent=Sys.Browser.InternetExplorer;Sys.Browser.version=parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]);if(Sys.Browser.version>=8)if(document.documentMode>=7)Sys.Browser.documentMode=document.documentMode;Sys.Browser.hasDebuggerStatement=true}else if(navigator.userAgent.indexOf(" Firefox/")>-1){Sys.Browser.agent=Sys.Browser.Firefox;Sys.Browser.version=parseFloat(navigator.userAgent.match(/Firefox\/(\d+\.\d+)/)[1]);Sys.Browser.name="Firefox";Sys.Browser.hasDebuggerStatement=true}else if(navigator.userAgent.indexOf(" AppleWebKit/")>-1){Sys.Browser.agent=Sys.Browser.Safari;Sys.Browser.version=parseFloat(navigator.userAgent.match(/AppleWebKit\/(\d+(\.\d+)?)/)[1]);Sys.Browser.name="Safari"}else if(navigator.userAgent.indexOf("Opera/")>-1)Sys.Browser.agent=Sys.Browser.Opera;Type.registerNamespace("Sys.UI");Sys._Debug=function(){};Sys._Debug.prototype={_appendConsole:function(a){if(typeof Debug!=="undefined"&&Debug.writeln)Debug.writeln(a);if(window.console&&window.console.log)window.console.log(a);if(window.opera)window.opera.postError(a);if(window.debugService)window.debugService.trace(a)},_appendTrace:function(b){var a=document.getElementById("TraceConsole");if(a&&a.tagName.toUpperCase()==="TEXTAREA")a.value+=b+"\n"},assert:function(c,a,b){if(!c){a=b&&this.assert.caller?String.format(Sys.Res.assertFailedCaller,a,this.assert.caller):String.format(Sys.Res.assertFailed,a);if(confirm(String.format(Sys.Res.breakIntoDebugger,a)))this.fail(a)}},clearTrace:function(){var a=document.getElementById("TraceConsole");if(a&&a.tagName.toUpperCase()==="TEXTAREA")a.value=""},fail:function(message){this._appendConsole(message);if(Sys.Browser.hasDebuggerStatement)eval("debugger")},trace:function(a){this._appendConsole(a);this._appendTrace(a)},traceDump:function(a,b){var c=this._traceDump(a,b,true)},_traceDump:function(a,c,f,b,d){c=c?c:"traceDump";b=b?b:"";if(a===null){this.trace(b+c+": null");return}switch(typeof a){case "undefined":this.trace(b+c+": Undefined");break;case "number":case "string":case "boolean":this.trace(b+c+": "+a);break;default:if(Date.isInstanceOfType(a)||RegExp.isInstanceOfType(a)){this.trace(b+c+": "+a.toString());break}if(!d)d=[];else if(Array.contains(d,a)){this.trace(b+c+": ...");return}Array.add(d,a);if(a==window||a===document||window.HTMLElement&&a instanceof HTMLElement||typeof a.nodeName==="string"){var k=a.tagName?a.tagName:"DomElement";if(a.id)k+=" - "+a.id;this.trace(b+c+" {"+k+"}")}else{var i=Object.getTypeName(a);this.trace(b+c+(typeof i==="string"?" {"+i+"}":""));if(b===""||f){b+=" ";var e,j,l,g,h;if(Array.isInstanceOfType(a)){j=a.length;for(e=0;e=0;d--){var k=h[d].trim();b=a[k];if(typeof b!=="number")throw Error.argument("value",String.format(Sys.Res.enumInvalidValue,c.split(",")[d].trim(),this.__typeName));j|=b}return j}}function Sys$Enum$toString(c){if(typeof c==="undefined"||c===null)return this.__string;var d=this.prototype,a;if(!this.__flags||c===0){for(a in d)if(d[a]===c)return a}else{var b=this.__sortedValues;if(!b){b=[];for(a in d)b[b.length]={key:a,value:d[a]};b.sort(function(a,b){return a.value-b.value});this.__sortedValues=b}var e=[],g=c;for(a=b.length-1;a>=0;a--){var h=b[a],f=h.value;if(f===0)continue;if((f&c)===f){e[e.length]=h.key;g-=f;if(g===0)break}}if(e.length&&g===0)return e.reverse().join(", ")}return ""}Type.prototype.registerEnum=function(b,c){Sys.__upperCaseTypes[b.toUpperCase()]=this;for(var a in this.prototype)this[a]=this.prototype[a];this.__typeName=b;this.parse=Sys$Enum$parse;this.__string=this.toString();this.toString=Sys$Enum$toString;this.__flags=c;this.__enum=true};Type.isEnum=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__enum};Type.isFlags=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__flags};Sys.EventHandlerList=function(){this._list={}};Sys.EventHandlerList.prototype={addHandler:function(b,a){Array.add(this._getEvent(b,true),a)},removeHandler:function(c,b){var a=this._getEvent(c);if(!a)return;Array.remove(a,b)},getHandler:function(b){var a=this._getEvent(b);if(!a||a.length===0)return null;a=Array.clone(a);return function(c,d){for(var b=0,e=a.length;b=0;c--)$removeHandler(a,b,d[c].handler)}a._events=null}},$removeHandler=Sys.UI.DomEvent.removeHandler=function(a,e,f){var d=null,c=a._events[e];for(var b=0,g=c.length;b=0)d.className=(a.substr(0,b)+" "+a.substring(b+c.length+1,a.length)).trim()};Sys.UI.DomElement.setLocation=function(b,c,d){var a=b.style;a.position="absolute";a.left=c+"px";a.top=d+"px"};Sys.UI.DomElement.toggleCssClass=function(b,a){if(Sys.UI.DomElement.containsCssClass(b,a))Sys.UI.DomElement.removeCssClass(b,a);else Sys.UI.DomElement.addCssClass(b,a)};Sys.UI.DomElement.getVisibilityMode=function(a){return a._visibilityMode===Sys.UI.VisibilityMode.hide?Sys.UI.VisibilityMode.hide:Sys.UI.VisibilityMode.collapse};Sys.UI.DomElement.setVisibilityMode=function(a,b){Sys.UI.DomElement._ensureOldDisplayMode(a);if(a._visibilityMode!==b){a._visibilityMode=b;if(Sys.UI.DomElement.getVisible(a)===false)if(a._visibilityMode===Sys.UI.VisibilityMode.hide)a.style.display=a._oldDisplayMode;else a.style.display="none";a._visibilityMode=b}};Sys.UI.DomElement.getVisible=function(b){var a=b.currentStyle||Sys.UI.DomElement._getCurrentStyle(b);if(!a)return true;return a.visibility!=="hidden"&&a.display!=="none"};Sys.UI.DomElement.setVisible=function(a,b){if(b!==Sys.UI.DomElement.getVisible(a)){Sys.UI.DomElement._ensureOldDisplayMode(a);a.style.visibility=b?"visible":"hidden";if(b||a._visibilityMode===Sys.UI.VisibilityMode.hide)a.style.display=a._oldDisplayMode;else a.style.display="none"}};Sys.UI.DomElement._ensureOldDisplayMode=function(a){if(!a._oldDisplayMode){var b=a.currentStyle||Sys.UI.DomElement._getCurrentStyle(a);a._oldDisplayMode=b?b.display:null;if(!a._oldDisplayMode||a._oldDisplayMode==="none")switch(a.tagName.toUpperCase()){case "DIV":case "P":case "ADDRESS":case "BLOCKQUOTE":case "BODY":case "COL":case "COLGROUP":case "DD":case "DL":case "DT":case "FIELDSET":case "FORM":case "H1":case "H2":case "H3":case "H4":case "H5":case "H6":case "HR":case "IFRAME":case "LEGEND":case "OL":case "PRE":case "TABLE":case "TD":case "TH":case "TR":case "UL":a._oldDisplayMode="block";break;case "LI":a._oldDisplayMode="list-item";break;default:a._oldDisplayMode="inline"}}};Sys.UI.DomElement._getWindow=function(a){var b=a.ownerDocument||a.document||a;return b.defaultView||b.parentWindow};Sys.UI.DomElement._getCurrentStyle=function(a){if(a.nodeType===3)return null;var c=Sys.UI.DomElement._getWindow(a);if(a.documentElement)a=a.documentElement;var b=c&&a!==c&&c.getComputedStyle?c.getComputedStyle(a,null):a.currentStyle||a.style;if(!b&&Sys.Browser.agent===Sys.Browser.Safari&&a.style){var g=a.style.display,f=a.style.position;a.style.position="absolute";a.style.display="block";var e=c.getComputedStyle(a,null);a.style.display=g;a.style.position=f;b={};for(var d in e)b[d]=e[d];b.display="none"}return b};Sys.IContainer=function(){};Sys.IContainer.prototype={};Sys.IContainer.registerInterface("Sys.IContainer");Sys._ScriptLoader=function(){this._scriptsToLoad=null;this._sessions=[];this._scriptLoadedDelegate=Function.createDelegate(this,this._scriptLoadedHandler)};Sys._ScriptLoader.prototype={dispose:function(){this._stopSession();this._loading=false;if(this._events)delete this._events;this._sessions=null;this._currentSession=null;this._scriptLoadedDelegate=null},loadScripts:function(d,b,c,a){var e={allScriptsLoadedCallback:b,scriptLoadFailedCallback:c,scriptLoadTimeoutCallback:a,scriptsToLoad:this._scriptsToLoad,scriptTimeout:d};this._scriptsToLoad=null;this._sessions[this._sessions.length]=e;if(!this._loading)this._nextSession()},notifyScriptLoaded:function(){if(!this._loading)return;this._currentTask._notified++;if(Sys.Browser.agent===Sys.Browser.Safari)if(this._currentTask._notified===1)window.setTimeout(Function.createDelegate(this,function(){this._scriptLoadedHandler(this._currentTask.get_scriptElement(),true)}),0)},queueCustomScriptTag:function(a){if(!this._scriptsToLoad)this._scriptsToLoad=[];Array.add(this._scriptsToLoad,a)},queueScriptBlock:function(a){if(!this._scriptsToLoad)this._scriptsToLoad=[];Array.add(this._scriptsToLoad,{text:a})},queueScriptReference:function(a){if(!this._scriptsToLoad)this._scriptsToLoad=[];Array.add(this._scriptsToLoad,{src:a})},_createScriptElement:function(c){var a=document.createElement("script");a.type="text/javascript";for(var b in c)a[b]=c[b];return a},_loadScriptsInternal:function(){var b=this._currentSession;if(b.scriptsToLoad&&b.scriptsToLoad.length>0){var c=Array.dequeue(b.scriptsToLoad),a=this._createScriptElement(c);if(a.text&&Sys.Browser.agent===Sys.Browser.Safari){a.innerHTML=a.text;delete a.text}if(typeof c.src==="string"){this._currentTask=new Sys._ScriptLoaderTask(a,this._scriptLoadedDelegate);this._currentTask.execute()}else{document.getElementsByTagName("head")[0].appendChild(a);Sys._ScriptLoader._clearScript(a);this._loadScriptsInternal()}}else{this._stopSession();var d=b.allScriptsLoadedCallback;if(d)d(this);this._nextSession()}},_nextSession:function(){if(this._sessions.length===0){this._loading=false;this._currentSession=null;return}this._loading=true;var a=Array.dequeue(this._sessions);this._currentSession=a;if(a.scriptTimeout>0)this._timeoutCookie=window.setTimeout(Function.createDelegate(this,this._scriptLoadTimeoutHandler),a.scriptTimeout*1000);this._loadScriptsInternal()},_raiseError:function(a){var c=this._currentSession.scriptLoadFailedCallback,b=this._currentTask.get_scriptElement();this._stopSession();if(c){c(this,b,a);this._nextSession()}else{this._loading=false;throw Sys._ScriptLoader._errorScriptLoadFailed(b.src,a)}},_scriptLoadedHandler:function(a,b){if(b&&this._currentTask._notified)if(this._currentTask._notified>1)this._raiseError(true);else{Array.add(Sys._ScriptLoader._getLoadedScripts(),a.src);this._currentTask.dispose();this._currentTask=null;this._loadScriptsInternal()}else this._raiseError(false)},_scriptLoadTimeoutHandler:function(){var a=this._currentSession.scriptLoadTimeoutCallback;this._stopSession();if(a)a(this);this._nextSession()},_stopSession:function(){if(this._timeoutCookie){window.clearTimeout(this._timeoutCookie);this._timeoutCookie=null}if(this._currentTask){this._currentTask.dispose();this._currentTask=null}}};Sys._ScriptLoader.registerClass("Sys._ScriptLoader",null,Sys.IDisposable);Sys._ScriptLoader.getInstance=function(){var a=Sys._ScriptLoader._activeInstance;if(!a)a=Sys._ScriptLoader._activeInstance=new Sys._ScriptLoader;return a};Sys._ScriptLoader.isScriptLoaded=function(b){var a=document.createElement("script");a.src=b;return Array.contains(Sys._ScriptLoader._getLoadedScripts(),a.src)};Sys._ScriptLoader.readLoadedScripts=function(){if(!Sys._ScriptLoader._referencedScripts){var b=Sys._ScriptLoader._referencedScripts=[],c=document.getElementsByTagName("script");for(i=c.length-1;i>=0;i--){var d=c[i],a=d.src;if(a.length)if(!Array.contains(b,a))Array.add(b,a)}}};Sys._ScriptLoader._clearScript=function(a){if(!Sys.Debug.isDebug)a.parentNode.removeChild(a)};Sys._ScriptLoader._errorScriptLoadFailed=function(b,d){var a;if(d)a=Sys.Res.scriptLoadMultipleCallbacks;else a=Sys.Res.scriptLoadFailed;var e="Sys.ScriptLoadFailedException: "+String.format(a,b),c=Error.create(e,{name:"Sys.ScriptLoadFailedException","scriptUrl":b});c.popStackFrame();return c};Sys._ScriptLoader._getLoadedScripts=function(){if(!Sys._ScriptLoader._referencedScripts){Sys._ScriptLoader._referencedScripts=[];Sys._ScriptLoader.readLoadedScripts()}return Sys._ScriptLoader._referencedScripts};Sys._ScriptLoaderTask=function(b,a){this._scriptElement=b;this._completedCallback=a;this._notified=0};Sys._ScriptLoaderTask.prototype={get_scriptElement:function(){return this._scriptElement},dispose:function(){if(this._disposed)return;this._disposed=true;this._removeScriptElementHandlers();Sys._ScriptLoader._clearScript(this._scriptElement);this._scriptElement=null},execute:function(){this._addScriptElementHandlers();document.getElementsByTagName("head")[0].appendChild(this._scriptElement)},_addScriptElementHandlers:function(){this._scriptLoadDelegate=Function.createDelegate(this,this._scriptLoadHandler);if(Sys.Browser.agent!==Sys.Browser.InternetExplorer){this._scriptElement.readyState="loaded";$addHandler(this._scriptElement,"load",this._scriptLoadDelegate)}else $addHandler(this._scriptElement,"readystatechange",this._scriptLoadDelegate);if(this._scriptElement.addEventListener){this._scriptErrorDelegate=Function.createDelegate(this,this._scriptErrorHandler);this._scriptElement.addEventListener("error",this._scriptErrorDelegate,false)}},_removeScriptElementHandlers:function(){if(this._scriptLoadDelegate){var a=this.get_scriptElement();if(Sys.Browser.agent!==Sys.Browser.InternetExplorer)$removeHandler(a,"load",this._scriptLoadDelegate);else $removeHandler(a,"readystatechange",this._scriptLoadDelegate);if(this._scriptErrorDelegate){this._scriptElement.removeEventListener("error",this._scriptErrorDelegate,false);this._scriptErrorDelegate=null}this._scriptLoadDelegate=null}},_scriptErrorHandler:function(){if(this._disposed)return;this._completedCallback(this.get_scriptElement(),false)},_scriptLoadHandler:function(){if(this._disposed)return;var a=this.get_scriptElement();if(a.readyState!=="loaded"&&a.readyState!=="complete")return;var b=this;window.setTimeout(function(){b._completedCallback(a,true)},0)}};Sys._ScriptLoaderTask.registerClass("Sys._ScriptLoaderTask",null,Sys.IDisposable);Sys.ApplicationLoadEventArgs=function(b,a){Sys.ApplicationLoadEventArgs.initializeBase(this);this._components=b;this._isPartialLoad=a};Sys.ApplicationLoadEventArgs.prototype={get_components:function(){return this._components},get_isPartialLoad:function(){return this._isPartialLoad}};Sys.ApplicationLoadEventArgs.registerClass("Sys.ApplicationLoadEventArgs",Sys.EventArgs);Sys.HistoryEventArgs=function(a){Sys.HistoryEventArgs.initializeBase(this);this._state=a};Sys.HistoryEventArgs.prototype={get_state:function(){return this._state}};Sys.HistoryEventArgs.registerClass("Sys.HistoryEventArgs",Sys.EventArgs);Sys._Application=function(){Sys._Application.initializeBase(this);this._disposableObjects=[];this._components={};this._createdComponents=[];this._secondPassComponents=[];this._appLoadHandler=null;this._beginRequestHandler=null;this._clientId=null;this._currentEntry="";this._endRequestHandler=null;this._history=null;this._enableHistory=false;this._historyFrame=null;this._historyInitialized=false;this._historyInitialLength=0;this._historyLength=0;this._historyPointIsNew=false;this._ignoreTimer=false;this._initialState=null;this._state={};this._timerCookie=0;this._timerHandler=null;this._uniqueId=null;this._unloadHandlerDelegate=Function.createDelegate(this,this._unloadHandler);this._loadHandlerDelegate=Function.createDelegate(this,this._loadHandler);Sys.UI.DomEvent.addHandler(window,"unload",this._unloadHandlerDelegate);Sys.UI.DomEvent.addHandler(window,"load",this._loadHandlerDelegate)};Sys._Application.prototype={_creatingComponents:false,_disposing:false,get_isCreatingComponents:function(){return this._creatingComponents},get_stateString:function(){var a=window.location.hash;if(this._isSafari2()){var b=this._getHistory();if(b)a=b[window.history.length-this._historyInitialLength]}if(a.length>0&&a.charAt(0)==="#")a=a.substring(1);if(Sys.Browser.agent===Sys.Browser.Firefox)a=this._serializeState(this._deserializeState(a,true));return a},get_enableHistory:function(){return this._enableHistory},set_enableHistory:function(a){this._enableHistory=a},add_init:function(a){if(this._initialized)a(this,Sys.EventArgs.Empty);else this.get_events().addHandler("init",a)},remove_init:function(a){this.get_events().removeHandler("init",a)},add_load:function(a){this.get_events().addHandler("load",a)},remove_load:function(a){this.get_events().removeHandler("load",a)},add_navigate:function(a){this.get_events().addHandler("navigate",a)},remove_navigate:function(a){this.get_events().removeHandler("navigate",a)},add_unload:function(a){this.get_events().addHandler("unload",a)},remove_unload:function(a){this.get_events().removeHandler("unload",a)},addComponent:function(a){this._components[a.get_id()]=a},addHistoryPoint:function(c,f){this._ensureHistory();var b=this._state;for(var a in c){var d=c[a];if(d===null){if(typeof b[a]!=="undefined")delete b[a]}else b[a]=d}var e=this._serializeState(b);this._historyPointIsNew=true;this._setState(e,f);this._raiseNavigate()},beginCreateComponents:function(){this._creatingComponents=true},dispose:function(){if(!this._disposing){this._disposing=true;if(this._timerCookie){window.clearTimeout(this._timerCookie);delete this._timerCookie}if(this._endRequestHandler){Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this._endRequestHandler);delete this._endRequestHandler}if(this._beginRequestHandler){Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(this._beginRequestHandler);delete this._beginRequestHandler}if(window.pageUnload)window.pageUnload(this,Sys.EventArgs.Empty);var c=this.get_events().getHandler("unload");if(c)c(this,Sys.EventArgs.Empty);var b=Array.clone(this._disposableObjects);for(var a=0,e=b.length;a'");d.write(""+(c||document.title)+"parent.Sys.Application._onIFrameLoad(\''+a+"');");d.close()}this._ignoreTimer=false;var h=this.get_stateString();this._currentEntry=a;if(a!==h){if(this._isSafari2()){var g=this._getHistory();g[window.history.length-this._historyInitialLength+1]=a;this._setHistory(g);this._historyLength=window.history.length+1;var b=document.createElement("form");b.method="get";b.action="#"+a;document.appendChild(b);b.submit();document.removeChild(b)}else window.location.hash=a;if(typeof c!=="undefined"&&c!==null)document.title=c}}},_unloadHandler:function(){this.dispose()},_updateHiddenField:function(b){if(this._clientId){var a=document.getElementById(this._clientId);if(a)a.value=b}}};Sys._Application.registerClass("Sys._Application",Sys.Component,Sys.IContainer);Sys.Application=new Sys._Application;var $find=Sys.Application.findComponent;Type.registerNamespace("Sys.Net");Sys.Net.WebRequestExecutor=function(){this._webRequest=null;this._resultObject=null};Sys.Net.WebRequestExecutor.prototype={get_webRequest:function(){return this._webRequest},_set_webRequest:function(a){this._webRequest=a},get_started:function(){throw Error.notImplemented()},get_responseAvailable:function(){throw Error.notImplemented()},get_timedOut:function(){throw Error.notImplemented()},get_aborted:function(){throw Error.notImplemented()},get_responseData:function(){throw Error.notImplemented()},get_statusCode:function(){throw Error.notImplemented()},get_statusText:function(){throw Error.notImplemented()},get_xml:function(){throw Error.notImplemented()},get_object:function(){if(!this._resultObject)this._resultObject=Sys.Serialization.JavaScriptSerializer.deserialize(this.get_responseData());return this._resultObject},executeRequest:function(){throw Error.notImplemented()},abort:function(){throw Error.notImplemented()},getResponseHeader:function(){throw Error.notImplemented()},getAllResponseHeaders:function(){throw Error.notImplemented()}};Sys.Net.WebRequestExecutor.registerClass("Sys.Net.WebRequestExecutor");Sys.Net.XMLDOM=function(d){if(!window.DOMParser){var c=["Msxml2.DOMDocument.3.0","Msxml2.DOMDocument"];for(var b=0,f=c.length;b0)this._timer=window.setTimeout(Function.createDelegate(this,this._onTimeout),d);this._xmlHttpRequest.send(c);this._started=true},getResponseHeader:function(b){var a;try{a=this._xmlHttpRequest.getResponseHeader(b)}catch(c){}if(!a)a="";return a},getAllResponseHeaders:function(){return this._xmlHttpRequest.getAllResponseHeaders()},get_responseData:function(){return this._xmlHttpRequest.responseText},get_statusCode:function(){var a=0;try{a=this._xmlHttpRequest.status}catch(b){}return a},get_statusText:function(){return this._xmlHttpRequest.statusText},get_xml:function(){var a=this._xmlHttpRequest.responseXML;if(!a||!a.documentElement){a=Sys.Net.XMLDOM(this._xmlHttpRequest.responseText);if(!a||!a.documentElement)return null}else if(navigator.userAgent.indexOf("MSIE")!==-1)a.setProperty("SelectionLanguage","XPath");if(a.documentElement.namespaceURI==="http://www.mozilla.org/newlayout/xml/parsererror.xml"&&a.documentElement.tagName==="parsererror")return null;if(a.documentElement.firstChild&&a.documentElement.firstChild.tagName==="parsererror")return null;return a},abort:function(){if(this._aborted||this._responseAvailable||this._timedOut)return;this._aborted=true;this._clearTimer();if(this._xmlHttpRequest&&!this._responseAvailable){this._xmlHttpRequest.onreadystatechange=Function.emptyMethod;this._xmlHttpRequest.abort();this._xmlHttpRequest=null;this._webRequest.completed(Sys.EventArgs.Empty)}}};Sys.Net.XMLHttpExecutor.registerClass("Sys.Net.XMLHttpExecutor",Sys.Net.WebRequestExecutor);Sys.Net._WebRequestManager=function(){this._defaultTimeout=0;this._defaultExecutorType="Sys.Net.XMLHttpExecutor"};Sys.Net._WebRequestManager.prototype={add_invokingRequest:function(a){this._get_eventHandlerList().addHandler("invokingRequest",a)},remove_invokingRequest:function(a){this._get_eventHandlerList().removeHandler("invokingRequest",a)},add_completedRequest:function(a){this._get_eventHandlerList().addHandler("completedRequest",a)},remove_completedRequest:function(a){this._get_eventHandlerList().removeHandler("completedRequest",a)},_get_eventHandlerList:function(){if(!this._events)this._events=new Sys.EventHandlerList;return this._events},get_defaultTimeout:function(){return this._defaultTimeout},set_defaultTimeout:function(a){this._defaultTimeout=a},get_defaultExecutorType:function(){return this._defaultExecutorType},set_defaultExecutorType:function(a){this._defaultExecutorType=a},executeRequest:function(webRequest){var executor=webRequest.get_executor();if(!executor){var failed=false;try{var executorType=eval(this._defaultExecutorType);executor=new executorType}catch(a){failed=true}webRequest.set_executor(executor)}if(executor.get_aborted())return;var evArgs=new Sys.Net.NetworkRequestEventArgs(webRequest),handler=this._get_eventHandlerList().getHandler("invokingRequest");if(handler)handler(this,evArgs);if(!evArgs.get_cancel())executor.executeRequest()}};Sys.Net._WebRequestManager.registerClass("Sys.Net._WebRequestManager");Sys.Net.WebRequestManager=new Sys.Net._WebRequestManager;Sys.Net.NetworkRequestEventArgs=function(a){Sys.Net.NetworkRequestEventArgs.initializeBase(this);this._webRequest=a};Sys.Net.NetworkRequestEventArgs.prototype={get_webRequest:function(){return this._webRequest}};Sys.Net.NetworkRequestEventArgs.registerClass("Sys.Net.NetworkRequestEventArgs",Sys.CancelEventArgs);Sys.Net.WebRequest=function(){this._url="";this._headers={};this._body=null;this._userContext=null;this._httpVerb=null;this._executor=null;this._invokeCalled=false;this._timeout=0};Sys.Net.WebRequest.prototype={add_completed:function(a){this._get_eventHandlerList().addHandler("completed",a)},remove_completed:function(a){this._get_eventHandlerList().removeHandler("completed",a)},completed:function(b){var a=Sys.Net.WebRequestManager._get_eventHandlerList().getHandler("completedRequest");if(a)a(this._executor,b);a=this._get_eventHandlerList().getHandler("completed");if(a)a(this._executor,b)},_get_eventHandlerList:function(){if(!this._events)this._events=new Sys.EventHandlerList;return this._events},get_url:function(){return this._url},set_url:function(a){this._url=a},get_headers:function(){return this._headers},get_httpVerb:function(){if(this._httpVerb===null){if(this._body===null)return "GET";return "POST"}return this._httpVerb},set_httpVerb:function(a){this._httpVerb=a},get_body:function(){return this._body},set_body:function(a){this._body=a},get_userContext:function(){return this._userContext},set_userContext:function(a){this._userContext=a},get_executor:function(){return this._executor},set_executor:function(a){this._executor=a;this._executor._set_webRequest(this)},get_timeout:function(){if(this._timeout===0)return Sys.Net.WebRequestManager.get_defaultTimeout();return this._timeout},set_timeout:function(a){this._timeout=a},getResolvedUrl:function(){return Sys.Net.WebRequest._resolveUrl(this._url)},invoke:function(){Sys.Net.WebRequestManager.executeRequest(this);this._invokeCalled=true}};Sys.Net.WebRequest._resolveUrl=function(b,a){if(b&&b.indexOf("://")!==-1)return b;if(!a||a.length===0){var d=document.getElementsByTagName("base")[0];if(d&&d.href&&d.href.length>0)a=d.href;else a=document.URL}var c=a.indexOf("?");if(c!==-1)a=a.substr(0,c);c=a.indexOf("#");if(c!==-1)a=a.substr(0,c);a=a.substr(0,a.lastIndexOf("/")+1);if(!b||b.length===0)return a;if(b.charAt(0)==="/"){var e=a.indexOf("://"),g=a.indexOf("/",e+3);return a.substr(0,g)+b}else{var f=a.lastIndexOf("/");return a.substr(0,f+1)+b}};Sys.Net.WebRequest._createQueryString=function(d,b){if(!b)b=encodeURIComponent;var a=new Sys.StringBuilder,f=0;for(var c in d){var e=d[c];if(typeof e==="function")continue;var g=Sys.Serialization.JavaScriptSerializer.serialize(e);if(f!==0)a.append("&");a.append(c);a.append("=");a.append(b(g));f++}return a.toString()};Sys.Net.WebRequest._createUrl=function(a,b){if(!b)return a;var d=Sys.Net.WebRequest._createQueryString(b);if(d.length>0){var c="?";if(a&&a.indexOf("?")!==-1)c="&";return a+c+d}else return a};Sys.Net.WebRequest.registerClass("Sys.Net.WebRequest");Sys.Net.WebServiceProxy=function(){};Sys.Net.WebServiceProxy.prototype={get_timeout:function(){return this._timeout},set_timeout:function(a){if(a<0)throw Error.argumentOutOfRange("value",a,Sys.Res.invalidTimeout);this._timeout=a},get_defaultUserContext:function(){return this._userContext},set_defaultUserContext:function(a){this._userContext=a},get_defaultSucceededCallback:function(){return this._succeeded},set_defaultSucceededCallback:function(a){this._succeeded=a},get_defaultFailedCallback:function(){return this._failed},set_defaultFailedCallback:function(a){this._failed=a},get_path:function(){return this._path},set_path:function(a){this._path=a},_invoke:function(d,e,g,f,c,b,a){if(c===null||typeof c==="undefined")c=this.get_defaultSucceededCallback();if(b===null||typeof b==="undefined")b=this.get_defaultFailedCallback();if(a===null||typeof a==="undefined")a=this.get_defaultUserContext();return Sys.Net.WebServiceProxy.invoke(d,e,g,f,c,b,a,this.get_timeout())}};Sys.Net.WebServiceProxy.registerClass("Sys.Net.WebServiceProxy");Sys.Net.WebServiceProxy.invoke=function(k,a,j,d,i,c,f,h){var b=new Sys.Net.WebRequest;b.get_headers()["Content-Type"]="application/json; charset=utf-8";if(!d)d={};var g=d;if(!j||!g)g={};b.set_url(Sys.Net.WebRequest._createUrl(k+"/"+encodeURIComponent(a),g));var e=null;if(!j){e=Sys.Serialization.JavaScriptSerializer.serialize(d);if(e==="{}")e=""}b.set_body(e);b.add_completed(l);if(h&&h>0)b.set_timeout(h);b.invoke();function l(d){if(d.get_responseAvailable()){var g=d.get_statusCode(),b=null;try{var e=d.getResponseHeader("Content-Type");if(e.startsWith("application/json"))b=d.get_object();else if(e.startsWith("text/xml"))b=d.get_xml();else b=d.get_responseData()}catch(m){}var k=d.getResponseHeader("jsonerror"),h=k==="true";if(h){if(b)b=new Sys.Net.WebServiceError(false,b.Message,b.StackTrace,b.ExceptionType)}else if(e.startsWith("application/json"))b=b.d;if(g<200||g>=300||h){if(c){if(!b||!h)b=new Sys.Net.WebServiceError(false,String.format(Sys.Res.webServiceFailedNoMsg,a),"","");b._statusCode=g;c(b,f,a)}}else if(i)i(b,f,a)}else{var j;if(d.get_timedOut())j=String.format(Sys.Res.webServiceTimedOut,a);else j=String.format(Sys.Res.webServiceFailedNoMsg,a);if(c)c(new Sys.Net.WebServiceError(d.get_timedOut(),j,"",""),f,a)}}return b};Sys.Net.WebServiceProxy._generateTypedConstructor=function(a){return function(b){if(b)for(var c in b)this[c]=b[c];this.__type=a}};Sys.Net.WebServiceError=function(c,d,b,a){this._timedOut=c;this._message=d;this._stackTrace=b;this._exceptionType=a;this._statusCode=-1};Sys.Net.WebServiceError.prototype={get_timedOut:function(){return this._timedOut},get_statusCode:function(){return this._statusCode},get_message:function(){return this._message},get_stackTrace:function(){return this._stackTrace},get_exceptionType:function(){return this._exceptionType}};Sys.Net.WebServiceError.registerClass("Sys.Net.WebServiceError");Type.registerNamespace("Sys.Services");Sys.Services._ProfileService=function(){Sys.Services._ProfileService.initializeBase(this);this.properties={}};Sys.Services._ProfileService.DefaultWebServicePath="";Sys.Services._ProfileService.prototype={_defaultLoadCompletedCallback:null,_defaultSaveCompletedCallback:null,_path:"",_timeout:0,get_defaultLoadCompletedCallback:function(){return this._defaultLoadCompletedCallback},set_defaultLoadCompletedCallback:function(a){this._defaultLoadCompletedCallback=a},get_defaultSaveCompletedCallback:function(){return this._defaultSaveCompletedCallback},set_defaultSaveCompletedCallback:function(a){this._defaultSaveCompletedCallback=a},get_path:function(){return this._path||""},load:function(c,d,e,f){var b,a;if(!c){a="GetAllPropertiesForCurrentUser";b={authenticatedUserOnly:false}}else{a="GetPropertiesForCurrentUser";b={properties:this._clonePropertyNames(c),authenticatedUserOnly:false}}this._invoke(this._get_path(),a,false,b,Function.createDelegate(this,this._onLoadComplete),Function.createDelegate(this,this._onLoadFailed),[d,e,f])},save:function(d,b,c,e){var a=this._flattenProperties(d,this.properties);this._invoke(this._get_path(),"SetPropertiesForCurrentUser",false,{values:a.value,authenticatedUserOnly:false},Function.createDelegate(this,this._onSaveComplete),Function.createDelegate(this,this._onSaveFailed),[b,c,e,a.count])},_clonePropertyNames:function(e){var c=[],d={};for(var b=0;b0)a.append(",");Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(b[c],a,false,g)}a.append("]")}else{if(Date.isInstanceOfType(b)){a.append('"\\/Date(');a.append(b.getTime());a.append(')\\/"');break}var d=[],f=0;for(var e in b){if(e.startsWith("$"))continue;if(e===Sys.Serialization.JavaScriptSerializer._serverTypeFieldName&&f!==0){d[f++]=d[0];d[0]=e}else d[f++]=e}if(i)d.sort();a.append("{");var j=false;for(c=0;c + /// + /// + /// + /// + /// +}; +Sys.Mvc.InsertionMode.prototype = { + replace: 0, + insertBefore: 1, + insertAfter: 2 +} +Sys.Mvc.InsertionMode.registerEnum('Sys.Mvc.InsertionMode', false); + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.AjaxContext + +Sys.Mvc.AjaxContext = function Sys_Mvc_AjaxContext(request, updateTarget, loadingElement, insertionMode) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + this._request = request; + this._updateTarget = updateTarget; + this._loadingElement = loadingElement; + this._insertionMode = insertionMode; +} +Sys.Mvc.AjaxContext.prototype = { + _insertionMode: 0, + _loadingElement: null, + _response: null, + _request: null, + _updateTarget: null, + + get_data: function Sys_Mvc_AjaxContext$get_data() { + /// + if (this._response) { + return this._response.get_responseData(); + } + else { + return null; + } + }, + + get_insertionMode: function Sys_Mvc_AjaxContext$get_insertionMode() { + /// + return this._insertionMode; + }, + + get_loadingElement: function Sys_Mvc_AjaxContext$get_loadingElement() { + /// + return this._loadingElement; + }, + + get_response: function Sys_Mvc_AjaxContext$get_response() { + /// + return this._response; + }, + set_response: function Sys_Mvc_AjaxContext$set_response(value) { + /// + this._response = value; + return value; + }, + + get_request: function Sys_Mvc_AjaxContext$get_request() { + /// + return this._request; + }, + + get_updateTarget: function Sys_Mvc_AjaxContext$get_updateTarget() { + /// + return this._updateTarget; + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.AsyncHyperlink + +Sys.Mvc.AsyncHyperlink = function Sys_Mvc_AsyncHyperlink() { +} +Sys.Mvc.AsyncHyperlink.handleClick = function Sys_Mvc_AsyncHyperlink$handleClick(anchor, evt, ajaxOptions) { + /// + /// + /// + /// + /// + /// + evt.preventDefault(); + Sys.Mvc.MvcHelpers._asyncRequest(anchor.href, 'post', '', anchor, ajaxOptions); +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.MvcHelpers + +Sys.Mvc.MvcHelpers = function Sys_Mvc_MvcHelpers() { +} +Sys.Mvc.MvcHelpers._serializeForm = function Sys_Mvc_MvcHelpers$_serializeForm(form) { + /// + /// + /// + var formElements = form.elements; + var formBody = new Sys.StringBuilder(); + var count = formElements.length; + for (var i = 0; i < count; i++) { + var element = formElements[i]; + var name = element.name; + if (!name || !name.length) { + continue; + } + var tagName = element.tagName.toUpperCase(); + if (tagName === 'INPUT') { + var inputElement = element; + var type = inputElement.type; + if ((type === 'text') || (type === 'password') || (type === 'hidden') || (((type === 'checkbox') || (type === 'radio')) && element.checked)) { + formBody.append(encodeURIComponent(name)); + formBody.append('='); + formBody.append(encodeURIComponent(inputElement.value)); + formBody.append('&'); + } + } + else if (tagName === 'SELECT') { + var selectElement = element; + var optionCount = selectElement.options.length; + for (var j = 0; j < optionCount; j++) { + var optionElement = selectElement.options[j]; + if (optionElement.selected) { + formBody.append(encodeURIComponent(name)); + formBody.append('='); + formBody.append(encodeURIComponent(optionElement.value)); + formBody.append('&'); + } + } + } + else if (tagName === 'TEXTAREA') { + formBody.append(encodeURIComponent(name)); + formBody.append('='); + formBody.append(encodeURIComponent((element.value))); + formBody.append('&'); + } + } + return formBody.toString(); +} +Sys.Mvc.MvcHelpers._asyncRequest = function Sys_Mvc_MvcHelpers$_asyncRequest(url, verb, body, triggerElement, ajaxOptions) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + if (ajaxOptions.confirm) { + if (!confirm(ajaxOptions.confirm)) { + return; + } + } + if (ajaxOptions.url) { + url = ajaxOptions.url; + } + if (ajaxOptions.httpMethod) { + verb = ajaxOptions.httpMethod; + } + if (body.length > 0 && !body.endsWith('&')) { + body += '&'; + } + body += 'X-Requested-With=XMLHttpRequest'; + var requestBody = ''; + if (verb.toUpperCase() === 'GET' || verb.toUpperCase() === 'DELETE') { + if (url.indexOf('?') > -1) { + if (!url.endsWith('&')) { + url += '&'; + } + url += body; + } + else { + url += '?'; + url += body; + } + } + else { + requestBody = body; + } + var request = new Sys.Net.WebRequest(); + request.set_url(url); + request.set_httpVerb(verb); + request.set_body(requestBody); + if (verb.toUpperCase() === 'PUT') { + request.get_headers()['Content-Type'] = 'application/x-www-form-urlencoded;'; + } + request.get_headers()['X-Requested-With'] = 'XMLHttpRequest'; + var updateElement = null; + if (ajaxOptions.updateTargetId) { + updateElement = $get(ajaxOptions.updateTargetId); + } + var loadingElement = null; + if (ajaxOptions.loadingElementId) { + loadingElement = $get(ajaxOptions.loadingElementId); + } + var ajaxContext = new Sys.Mvc.AjaxContext(request, updateElement, loadingElement, ajaxOptions.insertionMode); + var continueRequest = true; + if (ajaxOptions.onBegin) { + continueRequest = ajaxOptions.onBegin(ajaxContext) !== false; + } + if (loadingElement) { + Sys.UI.DomElement.setVisible(ajaxContext.get_loadingElement(), true); + } + if (continueRequest) { + request.add_completed(Function.createDelegate(null, function(executor) { + Sys.Mvc.MvcHelpers._onComplete(request, ajaxOptions, ajaxContext); + })); + request.invoke(); + } +} +Sys.Mvc.MvcHelpers._onComplete = function Sys_Mvc_MvcHelpers$_onComplete(request, ajaxOptions, ajaxContext) { + /// + /// + /// + /// + /// + /// + ajaxContext.set_response(request.get_executor()); + if (ajaxOptions.onComplete && ajaxOptions.onComplete(ajaxContext) === false) { + return; + } + var statusCode = ajaxContext.get_response().get_statusCode(); + if ((statusCode >= 200 && statusCode < 300) || statusCode === 304 || statusCode === 1223) { + if (statusCode !== 204 && statusCode !== 304 && statusCode !== 1223) { + var contentType = ajaxContext.get_response().getResponseHeader('Content-Type'); + if ((contentType) && (contentType.indexOf('application/x-javascript') !== -1)) { + eval(ajaxContext.get_data()); + } + else { + Sys.Mvc.MvcHelpers.updateDomElement(ajaxContext.get_updateTarget(), ajaxContext.get_insertionMode(), ajaxContext.get_data()); + } + } + if (ajaxOptions.onSuccess) { + ajaxOptions.onSuccess(ajaxContext); + } + } + else { + if (ajaxOptions.onFailure) { + ajaxOptions.onFailure(ajaxContext); + } + } + if (ajaxContext.get_loadingElement()) { + Sys.UI.DomElement.setVisible(ajaxContext.get_loadingElement(), false); + } +} +Sys.Mvc.MvcHelpers.updateDomElement = function Sys_Mvc_MvcHelpers$updateDomElement(target, insertionMode, content) { + /// + /// + /// + /// + /// + /// + if (target) { + switch (insertionMode) { + case Sys.Mvc.InsertionMode.replace: + target.innerHTML = content; + break; + case Sys.Mvc.InsertionMode.insertBefore: + if (content && content.length > 0) { + target.innerHTML = content + target.innerHTML.trimStart(); + } + break; + case Sys.Mvc.InsertionMode.insertAfter: + if (content && content.length > 0) { + target.innerHTML = target.innerHTML.trimEnd() + content; + } + break; + } + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.AsyncForm + +Sys.Mvc.AsyncForm = function Sys_Mvc_AsyncForm() { +} +Sys.Mvc.AsyncForm.handleSubmit = function Sys_Mvc_AsyncForm$handleSubmit(form, evt, ajaxOptions) { + /// + /// + /// + /// + /// + /// + evt.preventDefault(); + var body = Sys.Mvc.MvcHelpers._serializeForm(form); + Sys.Mvc.MvcHelpers._asyncRequest(form.action, form.method || 'post', body, form, ajaxOptions); +} + + +Sys.Mvc.AjaxContext.registerClass('Sys.Mvc.AjaxContext'); +Sys.Mvc.AsyncHyperlink.registerClass('Sys.Mvc.AsyncHyperlink'); +Sys.Mvc.MvcHelpers.registerClass('Sys.Mvc.MvcHelpers'); +Sys.Mvc.AsyncForm.registerClass('Sys.Mvc.AsyncForm'); + +// ---- Do not remove this footer ---- +// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) +// ----------------------------------- diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/MicrosoftMvcAjax.js b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/MicrosoftMvcAjax.js new file mode 100644 index 00000000..6d6a7e82 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/MicrosoftMvcAjax.js @@ -0,0 +1,23 @@ +//---------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All rights reserved. +//---------------------------------------------------------- +// MicrosoftMvcAjax.js + +Type.registerNamespace('Sys.Mvc');Sys.Mvc.$create_AjaxOptions=function(){return {};} +Sys.Mvc.InsertionMode=function(){};Sys.Mvc.InsertionMode.prototype = {replace:0,insertBefore:1,insertAfter:2} +Sys.Mvc.InsertionMode.registerEnum('Sys.Mvc.InsertionMode',false);Sys.Mvc.AjaxContext=function(request,updateTarget,loadingElement,insertionMode){this.$3=request;this.$4=updateTarget;this.$1=loadingElement;this.$0=insertionMode;} +Sys.Mvc.AjaxContext.prototype={$0:0,$1:null,$2:null,$3:null,$4:null,get_data:function(){if(this.$2){return this.$2.get_responseData();}else{return null;}},get_insertionMode:function(){return this.$0;},get_loadingElement:function(){return this.$1;},get_response:function(){return this.$2;},set_response:function(value){this.$2=value;return value;},get_request:function(){return this.$3;},get_updateTarget:function(){return this.$4;}} +Sys.Mvc.AsyncHyperlink=function(){} +Sys.Mvc.AsyncHyperlink.handleClick=function(anchor,evt,ajaxOptions){evt.preventDefault();Sys.Mvc.MvcHelpers.$1(anchor.href,'post','',anchor,ajaxOptions);} +Sys.Mvc.MvcHelpers=function(){} +Sys.Mvc.MvcHelpers.$0=function($p0){var $0=$p0.elements;var $1=new Sys.StringBuilder();var $2=$0.length;for(var $3=0;$3<$2;$3++){var $4=$0[$3];var $5=$4.name;if(!$5||!$5.length){continue;}var $6=$4.tagName.toUpperCase();if($6==='INPUT'){var $7=$4;var $8=$7.type;if(($8==='text')||($8==='password')||($8==='hidden')||((($8==='checkbox')||($8==='radio'))&&$4.checked)){$1.append(encodeURIComponent($5));$1.append('=');$1.append(encodeURIComponent($7.value));$1.append('&');}}else if($6==='SELECT'){var $9=$4;var $A=$9.options.length;for(var $B=0;$B<$A;$B++){var $C=$9.options[$B];if($C.selected){$1.append(encodeURIComponent($5));$1.append('=');$1.append(encodeURIComponent($C.value));$1.append('&');}}}else if($6==='TEXTAREA'){$1.append(encodeURIComponent($5));$1.append('=');$1.append(encodeURIComponent(($4.value)));$1.append('&');}}return $1.toString();} +Sys.Mvc.MvcHelpers.$1=function($p0,$p1,$p2,$p3,$p4){if($p4.confirm){if(!confirm($p4.confirm)){return;}}if($p4.url){$p0=$p4.url;}if($p4.httpMethod){$p1=$p4.httpMethod;}if($p2.length>0&&!$p2.endsWith('&')){$p2+='&';}$p2+='X-Requested-With=XMLHttpRequest';var $0='';if($p1.toUpperCase()==='GET'||$p1.toUpperCase()==='DELETE'){if($p0.indexOf('?')>-1){if(!$p0.endsWith('&')){$p0+='&';}$p0+=$p2;}else{$p0+='?';$p0+=$p2;}}else{$0=$p2;}var $1=new Sys.Net.WebRequest();$1.set_url($p0);$1.set_httpVerb($p1);$1.set_body($0);if($p1.toUpperCase()==='PUT'){$1.get_headers()['Content-Type']='application/x-www-form-urlencoded;';}$1.get_headers()['X-Requested-With']='XMLHttpRequest';var $2=null;if($p4.updateTargetId){$2=$get($p4.updateTargetId);}var $3=null;if($p4.loadingElementId){$3=$get($p4.loadingElementId);}var $4=new Sys.Mvc.AjaxContext($1,$2,$3,$p4.insertionMode);var $5=true;if($p4.onBegin){$5=$p4.onBegin($4)!==false;}if($3){Sys.UI.DomElement.setVisible($4.get_loadingElement(),true);}if($5){$1.add_completed(Function.createDelegate(null,function($p1_0){ +Sys.Mvc.MvcHelpers.$2($1,$p4,$4);}));$1.invoke();}} +Sys.Mvc.MvcHelpers.$2=function($p0,$p1,$p2){$p2.set_response($p0.get_executor());if($p1.onComplete&&$p1.onComplete($p2)===false){return;}var $0=$p2.get_response().get_statusCode();if(($0>=200&&$0<300)||$0===304||$0===1223){if($0!==204&&$0!==304&&$0!==1223){var $1=$p2.get_response().getResponseHeader('Content-Type');if(($1)&&($1.indexOf('application/x-javascript')!==-1)){eval($p2.get_data());}else{Sys.Mvc.MvcHelpers.updateDomElement($p2.get_updateTarget(),$p2.get_insertionMode(),$p2.get_data());}}if($p1.onSuccess){$p1.onSuccess($p2);}}else{if($p1.onFailure){$p1.onFailure($p2);}}if($p2.get_loadingElement()){Sys.UI.DomElement.setVisible($p2.get_loadingElement(),false);}} +Sys.Mvc.MvcHelpers.updateDomElement=function(target,insertionMode,content){if(target){switch(insertionMode){case 0:target.innerHTML=content;break;case 1:if(content&&content.length>0){target.innerHTML=content+target.innerHTML.trimStart();}break;case 2:if(content&&content.length>0){target.innerHTML=target.innerHTML.trimEnd()+content;}break;}}} +Sys.Mvc.AsyncForm=function(){} +Sys.Mvc.AsyncForm.handleSubmit=function(form,evt,ajaxOptions){evt.preventDefault();var $0=Sys.Mvc.MvcHelpers.$0(form);Sys.Mvc.MvcHelpers.$1(form.action,form.method||'post',$0,form,ajaxOptions);} +Sys.Mvc.AjaxContext.registerClass('Sys.Mvc.AjaxContext');Sys.Mvc.AsyncHyperlink.registerClass('Sys.Mvc.AsyncHyperlink');Sys.Mvc.MvcHelpers.registerClass('Sys.Mvc.MvcHelpers');Sys.Mvc.AsyncForm.registerClass('Sys.Mvc.AsyncForm'); +// ---- Do not remove this footer ---- +// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) +// ----------------------------------- diff --git a/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/jquery-1.3.2-vsdoc.js b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/jquery-1.3.2-vsdoc.js new file mode 100644 index 00000000..27aefb87 --- /dev/null +++ b/SparkleShare/Windows/tools/gettext-cs-utils/Gettext.CsUtils/Samples/Gettext.Samples.Mvc/Scripts/jquery-1.3.2-vsdoc.js @@ -0,0 +1,6255 @@ +/* + * This file has been commented to support Visual Studio Intellisense. + * You should not use this file at runtime inside the browser--it is only + * intended to be used only for design-time IntelliSense. Please use the + * standard jQuery library for all production use. + * + * Comment version: 1.3.2a + */ + +/* + * jQuery JavaScript Library v1.3.2 + * + * Copyright (c) 2009 John Resig, http://jquery.com/ + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) + * Revision: 6246 + */ + +(function(){ + +var + // Will speed up references to window, and allows munging its name. + window = this, + // Will speed up references to undefined, and allows munging its name. + undefined, + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + // Map over the $ in case of overwrite + _$ = window.$, + + jQuery = window.jQuery = window.$ = function(selector, context) { + /// + /// 1: $(expression, context) - This function accepts a string containing a CSS selector which is then used to match a set of elements. + /// 2: $(html) - Create DOM elements on-the-fly from the provided String of raw HTML. + /// 3: $(elements) - Wrap jQuery functionality around a single or multiple DOM Element(s). + /// 4: $(callback) - A shorthand for $(document).ready(). + /// + /// + /// 1: expression - An expression to search with. + /// 2: html - A string of HTML to create on the fly. + /// 3: elements - DOM element(s) to be encapsulated by a jQuery object. + /// 4: callback - The function to execute when the DOM is ready. + /// + /// + /// 1: context - A DOM Element, Document or jQuery to use as context. + /// + /// + /// The DOM node context originally passed to jQuery() (if none was passed then context will be equal to the document). + /// + /// + /// A selector representing selector originally passed to jQuery(). + /// + /// + + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context ); + }, + + // A simple way to check for HTML strings or ID strings + // (both of which we optimize for) + quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/, + // Is it a simple selector + isSimple = /^.[^:#\[\.,]*$/; + +jQuery.fn = jQuery.prototype = { + init: function( selector, context ) { + /// + /// 1: $(expression, context) - This function accepts a string containing a CSS selector which is then used to match a set of elements. + /// 2: $(html) - Create DOM elements on-the-fly from the provided String of raw HTML. + /// 3: $(elements) - Wrap jQuery functionality around a single or multiple DOM Element(s). + /// 4: $(callback) - A shorthand for $(document).ready(). + /// + /// + /// 1: expression - An expression to search with. + /// 2: html - A string of HTML to create on the fly. + /// 3: elements - DOM element(s) to be encapsulated by a jQuery object. + /// 4: callback - The function to execute when the DOM is ready. + /// + /// + /// 1: context - A DOM Element, Document or jQuery to use as context. + /// + /// + + // Make sure that a selection was provided + selector = selector || document; + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this[0] = selector; + this.length = 1; + this.context = selector; + return this; + } + // Handle HTML strings + if (typeof selector === "string") { + // Are we dealing with HTML string or an ID? + var match = quickExpr.exec(selector); + + // Verify a match, and that no context was specified for #id + if (match && (match[1] || !context)) { + + // HANDLE: $(html) -> $(array) + if (match[1]) + selector = jQuery.clean([match[1]], context); + + // HANDLE: $("#id") + else { + var elem = document.getElementById(match[3]); + + // Handle the case where IE and Opera return items + // by name instead of ID + if (elem && elem.id != match[3]) + return jQuery().find(selector); + + // Otherwise, we inject the element directly into the jQuery object + var ret = jQuery(elem || []); + ret.context = document; + ret.selector = selector; + return ret; + } + + // HANDLE: $(expr, [context]) + // (which is just equivalent to: $(content).find(expr) + } else + return jQuery(context).find(selector); + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) + return jQuery( document ).ready( selector ); + + // Make sure that old selector state is passed along + if ( selector.selector && selector.context ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return this.setArray(jQuery.isArray( selector ) ? + selector : + jQuery.makeArray(selector)); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.3.2", + + // The number of elements contained in the matched element set + size: function() { + /// + /// The number of elements currently matched. + /// Part of Core + /// + /// + + return this.length; + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + /// + /// Access a single matched element. num is used to access the + /// Nth element matched. + /// Part of Core + /// + /// + /// + /// Access the element in the Nth position. + /// + + return num == undefined ? + + // Return a 'clean' array + Array.prototype.slice.call( this ) : + + // Return just the object + this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + /// + /// Set the jQuery object to an array of elements, while maintaining + /// the stack. + /// Part of Core + /// + /// + /// + /// An array of elements + /// + + // Build a new jQuery matched element set + var ret = jQuery( elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) + ret.selector = this.selector + (this.selector ? " " : "") + selector; + else if ( name ) + ret.selector = this.selector + "." + name + "(" + selector + ")"; + + // Return the newly-formed element set + return ret; + }, + + // Force the current matched set of elements to become + // the specified array of elements (destroying the stack in the process) + // You should use pushStack() in order to do this, but maintain the stack + setArray: function( elems ) { + /// + /// Set the jQuery object to an array of elements. This operation is + /// completely destructive - be sure to use .pushStack() if you wish to maintain + /// the jQuery stack. + /// Part of Core + /// + /// + /// + /// An array of elements + /// + + // Resetting the length to 0, then using the native Array push + // is a super-fast way to populate an object with array-like properties + this.length = 0; + Array.prototype.push.apply( this, elems ); + + return this; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + /// + /// Execute a function within the context of every matched element. + /// This means that every time the passed-in function is executed + /// (which is once for every element matched) the 'this' keyword + /// points to the specific element. + /// Additionally, the function, when executed, is passed a single + /// argument representing the position of the element in the matched + /// set. + /// Part of Core + /// + /// + /// + /// A function to execute + /// + + return jQuery.each( this, callback, args ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + /// + /// Searches every matched element for the object and returns + /// the index of the element, if found, starting with zero. + /// Returns -1 if the object wasn't found. + /// Part of Core + /// + /// + /// + /// Object to search for + /// + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem && elem.jquery ? elem[0] : elem + , this ); + }, + + attr: function( name, value, type ) { + /// + /// Set a single property to a computed value, on all matched elements. + /// Instead of a value, a function is provided, that computes the value. + /// Part of DOM/Attributes + /// + /// + /// + /// The name of the property to set. + /// + /// + /// A function returning the value to set. + /// + + var options = name; + + // Look for the case where we're accessing a style value + if ( typeof name === "string" ) + if ( value === undefined ) + return this[0] && jQuery[ type || "attr" ]( this[0], name ); + + else { + options = {}; + options[ name ] = value; + } + + // Check to see if we're setting style values + return this.each(function(i){ + // Set all the styles + for ( name in options ) + jQuery.attr( + type ? + this.style : + this, + name, jQuery.prop( this, options[ name ], type, i, name ) + ); + }); + }, + + css: function( key, value ) { + /// + /// Set a single style property to a value, on all matched elements. + /// If a number is provided, it is automatically converted into a pixel value. + /// Part of CSS + /// + /// + /// + /// The name of the property to set. + /// + /// + /// The value to set the property to. + /// + + // ignore negative width and height values + if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 ) + value = undefined; + return this.attr( key, value, "curCSS" ); + }, + + text: function( text ) { + /// + /// Set the text contents of all matched elements. + /// Similar to html(), but escapes HTML (replace "<" and ">" with their + /// HTML entities). + /// Part of DOM/Attributes + /// + /// + /// + /// The text value to set the contents of the element to. + /// + + if ( typeof text !== "object" && text != null ) + return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); + + var ret = ""; + + jQuery.each( text || this, function(){ + jQuery.each( this.childNodes, function(){ + if ( this.nodeType != 8 ) + ret += this.nodeType != 1 ? + this.nodeValue : + jQuery.fn.text( [ this ] ); + }); + }); + + return ret; + }, + + wrapAll: function( html ) { + /// + /// Wrap all matched elements with a structure of other elements. + /// This wrapping process is most useful for injecting additional + /// stucture into a document, without ruining the original semantic + /// qualities of a document. + /// This works by going through the first element + /// provided and finding the deepest ancestor element within its + /// structure - it is that element that will en-wrap everything else. + /// This does not work with elements that contain text. Any necessary text + /// must be added after the wrapping is done. + /// Part of DOM/Manipulation + /// + /// + /// + /// A DOM element that will be wrapped around the target. + /// + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).clone(); + + if ( this[0].parentNode ) + wrap.insertBefore( this[0] ); + + wrap.map(function(){ + var elem = this; + + while ( elem.firstChild ) + elem = elem.firstChild; + + return elem; + }).append(this); + } + + return this; + }, + + wrapInner: function( html ) { + /// + /// Wraps the inner child contents of each matched elemenht (including text nodes) with an HTML structure. + /// + /// + /// A string of HTML or a DOM element that will be wrapped around the target contents. + /// + /// + + return this.each(function(){ + jQuery( this ).contents().wrapAll( html ); + }); + }, + + wrap: function( html ) { + /// + /// Wrap all matched elements with a structure of other elements. + /// This wrapping process is most useful for injecting additional + /// stucture into a document, without ruining the original semantic + /// qualities of a document. + /// This works by going through the first element + /// provided and finding the deepest ancestor element within its + /// structure - it is that element that will en-wrap everything else. + /// This does not work with elements that contain text. Any necessary text + /// must be added after the wrapping is done. + /// Part of DOM/Manipulation + /// + /// + /// + /// A DOM element that will be wrapped around the target. + /// + + return this.each(function(){ + jQuery( this ).wrapAll( html ); + }); + }, + + append: function() { + /// + /// Append content to the inside of every matched element. + /// This operation is similar to doing an appendChild to all the + /// specified elements, adding them into the document. + /// Part of DOM/Manipulation + /// + /// + /// + /// Content to append to the target + /// + + return this.domManip(arguments, true, function(elem){ + if (this.nodeType == 1) + this.appendChild( elem ); + }); + }, + + prepend: function() { + /// + /// Prepend content to the inside of every matched element. + /// This operation is the best way to insert elements + /// inside, at the beginning, of all matched elements. + /// Part of DOM/Manipulation + /// + /// + /// + /// Content to prepend to the target. + /// + + return this.domManip(arguments, true, function(elem){ + if (this.nodeType == 1) + this.insertBefore( elem, this.firstChild ); + }); + }, + + before: function() { + /// + /// Insert content before each of the matched elements. + /// Part of DOM/Manipulation + /// + /// + /// + /// Content to insert before each target. + /// + + return this.domManip(arguments, false, function(elem){ + this.parentNode.insertBefore( elem, this ); + }); + }, + + after: function() { + /// + /// Insert content after each of the matched elements. + /// Part of DOM/Manipulation + /// + /// + /// + /// Content to insert after each target. + /// + + return this.domManip(arguments, false, function(elem){ + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + }, + + end: function() { + /// + /// End the most recent 'destructive' operation, reverting the list of matched elements + /// back to its previous state. After an end operation, the list of matched elements will + /// revert to the last state of matched elements. + /// If there was no destructive operation before, an empty set is returned. + /// Part of DOM/Traversing + /// + /// + + return this.prevObject || jQuery( [] ); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: [].push, + sort: [].sort, + splice: [].splice, + + find: function( selector ) { + /// + /// Searches for all elements that match the specified expression. + /// This method is a good way to find additional descendant + /// elements with which to process. + /// All searching is done using a jQuery expression. The expression can be + /// written using CSS 1-3 Selector syntax, or basic XPath. + /// Part of DOM/Traversing + /// + /// + /// + /// An expression to search with. + /// + /// + + if ( this.length === 1 ) { + var ret = this.pushStack( [], "find", selector ); + ret.length = 0; + jQuery.find( selector, this[0], ret ); + return ret; + } else { + return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){ + return jQuery.find( selector, elem ); + })), "find", selector ); + } + }, + + clone: function( events ) { + /// + /// Clone matched DOM Elements and select the clones. + /// This is useful for moving copies of the elements to another + /// location in the DOM. + /// Part of DOM/Manipulation + /// + /// + /// + /// (Optional) Set to false if you don't want to clone all descendant nodes, in addition to the element itself. + /// + + // Do the clone + var ret = this.map(function(){ + if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { + // IE copies events bound via attachEvent when + // using cloneNode. Calling detachEvent on the + // clone will also remove the events from the orignal + // In order to get around this, we use innerHTML. + // Unfortunately, this means some modifications to + // attributes in IE that are actually only stored + // as properties will not be copied (such as the + // the name attribute on an input). + var html = this.outerHTML; + if ( !html ) { + var div = this.ownerDocument.createElement("div"); + div.appendChild( this.cloneNode(true) ); + html = div.innerHTML; + } + + return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0]; + } else + return this.cloneNode(true); + }); + + // Copy the events from the original to the clone + if ( events === true ) { + var orig = this.find("*").andSelf(), i = 0; + + ret.find("*").andSelf().each(function(){ + if ( this.nodeName !== orig[i].nodeName ) + return; + + var events = jQuery.data( orig[i], "events" ); + + for ( var type in events ) { + for ( var handler in events[ type ] ) { + jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); + } + } + + i++; + }); + } + + // Return the cloned set + return ret; + }, + + filter: function( selector ) { + /// + /// Removes all elements from the set of matched elements that do not + /// pass the specified filter. This method is used to narrow down + /// the results of a search. + /// }) + /// Part of DOM/Traversing + /// + /// + /// + /// A function to use for filtering + /// + /// + + return this.pushStack( + jQuery.isFunction( selector ) && + jQuery.grep(this, function(elem, i){ + return selector.call( elem, i ); + }) || + + jQuery.multiFilter( selector, jQuery.grep(this, function(elem){ + return elem.nodeType === 1; + }) ), "filter", selector ); + }, + + closest: function( selector ) { + /// + /// Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. + /// + /// + /// + /// An expression to filter the elements with. + /// + /// + + var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null, + closer = 0; + + return this.map(function(){ + var cur = this; + while ( cur && cur.ownerDocument ) { + if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) { + jQuery.data(cur, "closest", closer); + return cur; + } + cur = cur.parentNode; + closer++; + } + }); + }, + + not: function( selector ) { + /// + /// Removes any elements inside the array of elements from the set + /// of matched elements. This method is used to remove one or more + /// elements from a jQuery object. + /// Part of DOM/Traversing + /// + /// + /// A set of elements to remove from the jQuery set of matched elements. + /// + /// + + if ( typeof selector === "string" ) + // test special case where just one selector is passed in + if ( isSimple.test( selector ) ) + return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector ); + else + selector = jQuery.multiFilter( selector, this ); + + var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType; + return this.filter(function() { + return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector; + }); + }, + + add: function( selector ) { + /// + /// Adds one or more Elements to the set of matched elements. + /// Part of DOM/Traversing + /// + /// + /// One or more Elements to add + /// + /// + + return this.pushStack( jQuery.unique( jQuery.merge( + this.get(), + typeof selector === "string" ? + jQuery( selector ) : + jQuery.makeArray( selector ) + ))); + }, + + is: function( selector ) { + /// + /// Checks the current selection against an expression and returns true, + /// if at least one element of the selection fits the given expression. + /// Does return false, if no element fits or the expression is not valid. + /// filter(String) is used internally, therefore all rules that apply there + /// apply here, too. + /// Part of DOM/Traversing + /// + /// + /// + /// The expression with which to filter + /// + + return !!selector && jQuery.multiFilter( selector, this ).length > 0; + }, + + hasClass: function( selector ) { + /// + /// Checks the current selection against a class and returns whether at least one selection has a given class. + /// + /// The class to check against + /// True if at least one element in the selection has the class, otherwise false. + + return !!selector && this.is( "." + selector ); + }, + + val: function( value ) { + /// + /// Set the value of every matched element. + /// Part of DOM/Attributes + /// + /// + /// + /// Set the property to the specified value. + /// + + if ( value === undefined ) { + var elem = this[0]; + + if ( elem ) { + if( jQuery.nodeName( elem, 'option' ) ) + return (elem.attributes.value || {}).specified ? elem.value : elem.text; + + // We need to handle select boxes special + if ( jQuery.nodeName( elem, "select" ) ) { + var index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type == "select-one"; + + // Nothing was selected + if ( index < 0 ) + return null; + + // Loop through all the selected options + for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { + var option = options[ i ]; + + if ( option.selected ) { + // Get the specifc value for the option + value = jQuery(option).val(); + + // We don't need an array for one selects + if ( one ) + return value; + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + } + + // Everything else, we just grab the value + return (elem.value || "").replace(/\r/g, ""); + + } + + return undefined; + } + + if ( typeof value === "number" ) + value += ''; + + return this.each(function(){ + if ( this.nodeType != 1 ) + return; + + if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) ) + this.checked = (jQuery.inArray(this.value, value) >= 0 || + jQuery.inArray(this.name, value) >= 0); + + else if ( jQuery.nodeName( this, "select" ) ) { + var values = jQuery.makeArray(value); + + jQuery( "option", this ).each(function(){ + this.selected = (jQuery.inArray( this.value, values ) >= 0 || + jQuery.inArray( this.text, values ) >= 0); + }); + + if ( !values.length ) + this.selectedIndex = -1; + + } else + this.value = value; + }); + }, + + html: function( value ) { + /// + /// Set the html contents of every matched element. + /// This property is not available on XML documents. + /// Part of DOM/Attributes + /// + /// + /// + /// Set the html contents to the specified value. + /// + + return value === undefined ? + (this[0] ? + this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") : + null) : + this.empty().append( value ); + }, + + replaceWith: function( value ) { + /// + /// Replaces all matched element with the specified HTML or DOM elements. + /// + /// + /// The content with which to replace the matched elements. + /// + /// The element that was just replaced. + + return this.after( value ).remove(); + }, + + eq: function( i ) { + /// + /// Reduce the set of matched elements to a single element. + /// The position of the element in the set of matched elements + /// starts at 0 and goes to length - 1. + /// Part of Core + /// + /// + /// + /// pos The index of the element that you wish to limit to. + /// + + return this.slice( i, +i + 1 ); + }, + + slice: function() { + /// + /// Selects a subset of the matched elements. Behaves exactly like the built-in Array slice method. + /// + /// Where to start the subset (0-based). + /// Where to end the subset (not including the end element itself). + /// If omitted, ends at the end of the selection + /// The sliced elements + + return this.pushStack( Array.prototype.slice.apply( this, arguments ), + "slice", Array.prototype.slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + /// + /// This member is internal. + /// + /// + /// + + return this.pushStack( jQuery.map(this, function(elem, i){ + return callback.call( elem, i, elem ); + })); + }, + + andSelf: function() { + /// + /// Adds the previous selection to the current selection. + /// + /// + + return this.add( this.prevObject ); + }, + + domManip: function( args, table, callback ) { + /// + /// Args + /// + /// + /// Insert TBODY in TABLEs if one is not found. + /// + /// + /// If dir<0, process args in reverse order. + /// + /// + /// The function doing the DOM manipulation. + /// + /// + /// + /// Part of Core + /// + + if ( this[0] ) { + var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(), + scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ), + first = fragment.firstChild; + + if ( first ) + for ( var i = 0, l = this.length; i < l; i++ ) + callback.call( root(this[i], first), this.length > 1 || i > 0 ? + fragment.cloneNode(true) : fragment ); + + if ( scripts ) + jQuery.each( scripts, evalScript ); + } + + return this; + + function root( elem, cur ) { + return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ? + (elem.getElementsByTagName("tbody")[0] || + elem.appendChild(elem.ownerDocument.createElement("tbody"))) : + elem; + } + } +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +function evalScript( i, elem ) { + /// + /// This method is internal. + /// + /// + + if ( elem.src ) + jQuery.ajax({ + url: elem.src, + async: false, + dataType: "script" + }); + + else + jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); + + if ( elem.parentNode ) + elem.parentNode.removeChild( elem ); +} + +function now(){ + /// + /// Gets the current date. + /// + /// The current date. + return +new Date; +} + +jQuery.extend = jQuery.fn.extend = function() { + /// + /// Extend one object with one or more others, returning the original, + /// modified, object. This is a great utility for simple inheritance. + /// jQuery.extend(settings, options); + /// var settings = jQuery.extend({}, defaults, options); + /// Part of JavaScript + /// + /// + /// The object to extend + /// + /// + /// The object that will be merged into the first. + /// + /// + /// (optional) More objects to merge into the first + /// + /// + + // copy reference to target object + var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) + target = {}; + + // extend jQuery itself if only one argument is passed + if ( length == i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) + // Extend the base object + for ( var name in options ) { + var src = target[ name ], copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) + continue; + + // Recurse if we're merging object values + if ( deep && copy && typeof copy === "object" && !copy.nodeType ) + target[ name ] = jQuery.extend( deep, + // Never move original objects, clone them + src || ( copy.length != null ? [ ] : { } ) + , copy ); + + // Don't bring in undefined values + else if ( copy !== undefined ) + target[ name ] = copy; + + } + + // Return the modified object + return target; +}; + +// exclude the following css properties to add px +var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, + // cache defaultView + defaultView = document.defaultView || {}, + toString = Object.prototype.toString; + +jQuery.extend({ + noConflict: function( deep ) { + /// + /// Run this function to give control of the $ variable back + /// to whichever library first implemented it. This helps to make + /// sure that jQuery doesn't conflict with the $ object + /// of other libraries. + /// By using this function, you will only be able to access jQuery + /// using the 'jQuery' variable. For example, where you used to do + /// $("div p"), you now must do jQuery("div p"). + /// Part of Core + /// + /// + + window.$ = _$; + + if ( deep ) + window.jQuery = _jQuery; + + return jQuery; + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + /// + /// Determines if the parameter passed is a function. + /// + /// The object to check + /// True if the parameter is a function; otherwise false. + + return toString.call(obj) === "[object Function]"; + }, + + isArray: function(obj) { + /// + /// Determine if the parameter passed is an array. + /// + /// Object to test whether or not it is an array. + /// True if the parameter is a function; otherwise false. + + return toString.call(obj) === "[object Array]"; + }, + + // check if an element is in a (or is an) XML document + isXMLDoc: function( elem ) { + /// + /// Determines if the parameter passed is an XML document. + /// + /// The object to test + /// True if the parameter is an XML document; otherwise false. + + return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || + !!elem.ownerDocument && jQuery.isXMLDoc(elem.ownerDocument); + }, + + // Evalulates a script in a global context + globalEval: function( data ) { + /// + /// Internally evaluates a script in a global context. + /// + /// + + if ( data && /\S/.test(data) ) { + // Inspired by code by Andrea Giammarchi + // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html + var head = document.getElementsByTagName("head")[0] || document.documentElement, + script = document.createElement("script"); + + script.type = "text/javascript"; + if ( jQuery.support.scriptEval ) + script.appendChild( document.createTextNode( data ) ); + else + script.text = data; + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709). + head.insertBefore( script, head.firstChild ); + head.removeChild( script ); + } + }, + + nodeName: function( elem, name ) { + /// + /// Checks whether the specified element has the specified DOM node name. + /// + /// The element to examine + /// The node name to check + /// True if the specified node name matches the node's DOM node name; otherwise false + + return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + /// + /// A generic iterator function, which can be used to seemlessly + /// iterate over both objects and arrays. This function is not the same + /// as $().each() - which is used to iterate, exclusively, over a jQuery + /// object. This function can be used to iterate over anything. + /// The callback has two arguments:the key (objects) or index (arrays) as first + /// the first, and the value as the second. + /// Part of JavaScript + /// + /// + /// The object, or array, to iterate over. + /// + /// + /// The function that will be executed on every object. + /// + /// + + var name, i = 0, length = object.length; + + if ( args ) { + if ( length === undefined ) { + for ( name in object ) + if ( callback.apply( object[ name ], args ) === false ) + break; + } else + for ( ; i < length; ) + if ( callback.apply( object[ i++ ], args ) === false ) + break; + + // A special, fast, case for the most common use of each + } else { + if ( length === undefined ) { + for ( name in object ) + if ( callback.call( object[ name ], name, object[ name ] ) === false ) + break; + } else + for ( var value = object[0]; + i < length && callback.call( value, i, value ) !== false; value = object[++i] ){} + } + + return object; + }, + + prop: function( elem, value, type, i, name ) { + /// + /// This method is internal. + /// + /// + // This member is not documented within the jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.prop + + // Handle executable functions + if ( jQuery.isFunction( value ) ) + value = value.call( elem, i ); + + // Handle passing in a number to a CSS property + return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ? + value + "px" : + value; + }, + + className: { + // internal only, use addClass("class") + add: function( elem, classNames ) { + /// + /// Internal use only; use addClass('class') + /// + /// + + jQuery.each((classNames || "").split(/\s+/), function(i, className){ + if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) ) + elem.className += (elem.className ? " " : "") + className; + }); + }, + + // internal only, use removeClass("class") + remove: function( elem, classNames ) { + /// + /// Internal use only; use removeClass('class') + /// + /// + + if (elem.nodeType == 1) + elem.className = classNames !== undefined ? + jQuery.grep(elem.className.split(/\s+/), function(className){ + return !jQuery.className.has( classNames, className ); + }).join(" ") : + ""; + }, + + // internal only, use hasClass("class") + has: function( elem, className ) { + /// + /// Internal use only; use hasClass('class') + /// + /// + + return elem && jQuery.inArray(className, (elem.className || elem).toString().split(/\s+/)) > -1; + } + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + /// + /// Swap in/out style options. + /// + + var old = {}; + // Remember the old values, and insert the new ones + for ( var name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + callback.call( elem ); + + // Revert the old values + for ( var name in options ) + elem.style[ name ] = old[ name ]; + }, + + css: function( elem, name, force, extra ) { + /// + /// This method is internal only. + /// + /// + // This method is undocumented in jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.css + + if ( name == "width" || name == "height" ) { + var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ]; + + function getWH() { + val = name == "width" ? elem.offsetWidth : elem.offsetHeight; + + if ( extra === "border" ) + return; + + jQuery.each( which, function() { + if ( !extra ) + val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; + if ( extra === "margin" ) + val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; + else + val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; + }); + } + + if ( elem.offsetWidth !== 0 ) + getWH(); + else + jQuery.swap( elem, props, getWH ); + + return Math.max(0, Math.round(val)); + } + + return jQuery.curCSS( elem, name, force ); + }, + + curCSS: function( elem, name, force ) { + /// + /// This method is internal only. + /// + /// + // This method is undocumented in jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.curCSS + + var ret, style = elem.style; + + // We need to handle opacity special in IE + if ( name == "opacity" && !jQuery.support.opacity ) { + ret = jQuery.attr( style, "opacity" ); + + return ret == "" ? + "1" : + ret; + } + + // Make sure we're using the right name for getting the float value + if ( name.match( /float/i ) ) + name = styleFloat; + + if ( !force && style && style[ name ] ) + ret = style[ name ]; + + else if ( defaultView.getComputedStyle ) { + + // Only "float" is needed here + if ( name.match( /float/i ) ) + name = "float"; + + name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase(); + + var computedStyle = defaultView.getComputedStyle( elem, null ); + + if ( computedStyle ) + ret = computedStyle.getPropertyValue( name ); + + // We should always get a number back from opacity + if ( name == "opacity" && ret == "" ) + ret = "1"; + + } else if ( elem.currentStyle ) { + var camelCase = name.replace(/\-(\w)/g, function(all, letter){ + return letter.toUpperCase(); + }); + + ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) { + // Remember the original values + var left = style.left, rsLeft = elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + elem.runtimeStyle.left = elem.currentStyle.left; + style.left = ret || 0; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + elem.runtimeStyle.left = rsLeft; + } + } + + return ret; + }, + + clean: function( elems, context, fragment ) { + /// + /// This method is internal only. + /// + /// + // This method is undocumented in the jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.clean + + + context = context || document; + + // !context.createElement fails in IE with an error but returns typeof 'object' + if ( typeof context.createElement === "undefined" ) + context = context.ownerDocument || context[0] && context[0].ownerDocument || document; + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) { + var match = /^<(\w+)\s*\/?>$/.exec(elems[0]); + if ( match ) + return [ context.createElement( match[1] ) ]; + } + + var ret = [], scripts = [], div = context.createElement("div"); + + jQuery.each(elems, function(i, elem){ + if ( typeof elem === "number" ) + elem += ''; + + if ( !elem ) + return; + + // Convert html string into DOM nodes + if ( typeof elem === "string" ) { + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){ + return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? + all : + front + ">"; + }); + + // Trim whitespace, otherwise indexOf won't work as expected + var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase(); + + var wrap = + // option or optgroup + !tags.indexOf("", "" ] || + + !tags.indexOf("", "" ] || + + tags.match(/^<(thead|tbody|tfoot|colg|cap)/) && + [ 1, "", "
" ] || + + !tags.indexOf("", "" ] || + + // matched above + (!tags.indexOf("", "" ] || + + !tags.indexOf("", "" ] || + + // IE can't serialize and