From 94f0a590fc22d12f7b40cb9abfdafae75e3d401b Mon Sep 17 00:00:00 2001 From: Shikhar Date: Mon, 05 Jan 2009 21:28:35 +0000 Subject: Initial import --- diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" 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 "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" 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. + + To "convey" 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. + + An interactive user interface displays "Appropriate Legal Notices" +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. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" 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. + + The "System Libraries" 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 +"Major Component", 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. + + The "Corresponding Source" 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. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + 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. + + 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. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + 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. + + 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. + + 4. Conveying Verbatim Copies. + + 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. + + 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. + + 5. Conveying Modified Source Versions. + + 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: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + 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 + "keep intact all notices". + + 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. + + 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. + + 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 +"aggregate" 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. + + 6. Conveying Non-Source Forms. + + 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: + + 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + A "User Product" is either (1) a "consumer product", 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, "normally used" 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. + + "Installation Information" 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. + + 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). + + 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. + + 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. + + 7. Additional Terms. + + "Additional permissions" 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. + + 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. + + 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: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + 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 + + 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 + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + 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. + + All other non-permissive additional terms are considered "further +restrictions" 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. + + 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. + + 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. + + 8. Termination. + + 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). + + 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. + + 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. + + 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. + + 9. Acceptance Not Required for Having Copies. + + 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. + + 10. Automatic Licensing of Downstream Recipients. + + 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. + + An "entity transaction" 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. + + 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. + + 11. Patents. + + A "contributor" 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 "contributor version". + + A contributor's "essential patent claims" 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, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + 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. + + In the following three paragraphs, a "patent license" 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 "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + 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. "Knowingly relying" 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. + + 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. + + A patent license is "discriminatory" 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. + + 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. + + 12. No Surrender of Others' Freedom. + + 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. + + 13. Use with the GNU Affero General Public License. + + 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. + + 14. Revised Versions of this License. + + 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. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" 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. + + 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. + + 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. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + 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. + + 17. Interpretation of Sections 15 and 16. + + 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. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/activity/activity-sweetmail.svg b/activity/activity-sweetmail.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/activity/activity-sweetmail.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/activity/activity.info b/activity/activity.info new file mode 100644 index 0000000..68af9c5 --- /dev/null +++ b/activity/activity.info @@ -0,0 +1,7 @@ +[Activity] +name = Sweetmail +service_name = org.sugarlabs.Sweetmail +class = sweetmail.SweetmailActivity +icon = activity-sweetmail +activity_version = 2 +show_launcher = yes diff --git a/icons/add-attachment.svg b/icons/add-attachment.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/add-attachment.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/dummy.svg b/icons/dummy.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/dummy.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/send-email.svg b/icons/send-email.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/send-email.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-all.svg b/icons/tag-all.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-all.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-default.svg b/icons/tag-default.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-default.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-drafts.svg b/icons/tag-drafts.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-drafts.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-forwarded.svg b/icons/tag-forwarded.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-forwarded.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-has-attachment.svg b/icons/tag-has-attachment.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-has-attachment.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-inbox.svg b/icons/tag-inbox.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-inbox.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-junk.svg b/icons/tag-junk.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-junk.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-outbound.svg b/icons/tag-outbound.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-outbound.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-replied.svg b/icons/tag-replied.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-replied.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-sent.svg b/icons/tag-sent.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-sent.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-starred.svg b/icons/tag-starred.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-starred.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-trash.svg b/icons/tag-trash.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-trash.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/icons/tag-unseen.svg b/icons/tag-unseen.svg new file mode 100644 index 0000000..a2ebe84 --- /dev/null +++ b/icons/tag-unseen.svg @@ -0,0 +1,10 @@ + + + +]> + + + diff --git a/model/accounts.py b/model/accounts.py new file mode 100644 index 0000000..3288a83 --- /dev/null +++ b/model/accounts.py @@ -0,0 +1,55 @@ +# Copyright 2009 Shikhar Bhushan +# +# This file is part of the Sweetmail activity for Sugar. +# +# Sweetmail is free software: you can 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. +# +# Sweetmail is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Sweetmail. If not, see . + +class Account(): + + def __init__(self, host, port, auth_type, username, password): + self._host = host + self._port = port + self._auth_type = auth_type + self._username = username + self._password = password + +class StoreAccount(Account): + + def __init__(self, host, port, auth_type, username, password, ): + Account.__init__(self, host, port, auth_type, username, password) + self._del_on_retr = del_on_retr + + def retrieval_all(self, tracker): + raise NotImplementedError + +class TransportAccount(Account): + + def __init__(self, from_addr, host, port, auth_type, username, password): + Account.__init__(self, host, port, auth_type, username, password) + self._from_addr = from_addr + + def send(self, msgs, tracker): + raise NotImplementedError + +class DummyTransportAccount(): + + def send(self, msgs, tracker): + from tracker import notify + notify(_('No transport account cofigured')) + +class DummyStoreAccount(): + + def retrieve_all(self, tracker): + from tracker import notify + notify(_('No store account cofigured')) \ No newline at end of file diff --git a/model/mailstore.py b/model/mailstore.py new file mode 100644 index 0000000..e65bad5 --- /dev/null +++ b/model/mailstore.py @@ -0,0 +1,236 @@ +# Copyright 2009 Shikhar Bhushan +# +# This file is part of the Sweetmail activity for Sugar. +# +# Sweetmail is free software: you can 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. +# +# Sweetmail is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Sweetmail. If not, see . + +import email +import mailbox +import os +import sqlite3 as sqlite +import threading + +from gettext import gettext as _ + +import tags +from msginfo import MsgInfo + +class MailStore(object): + ''' + Stores messages in Maildir. Tag and header metadata + is stored in a relational database. + Tags are uniquely identified by a 'uid' and messages by a 'key'. + Methods to manipulate tags and messages are provided. + ''' + + def __init__(self, path): + + dir = os.path.join(path, 'mail') + self.maildir = mailbox.Maildir(dir, None) + + self._dbfile = os.path.join(path, 'metadata.db') + self._cons = {} + + con = self.get_connection() + con.executescript(''' + CREATE TABLE IF NOT EXISTS tags ( + type INTEGER NOT NULL, + uid INTEGER PRIMARY KEY NOT NULL, + label TEXT NOT NULL, + icon TEXT NOT NULL, + pos INTEGER NOT NULL, + query TEXT + ); + + CREATE TABLE IF NOT EXISTS associations ( + key TEXT NOT NULL, + uid INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS metadata ( + key TEXT PRIMARY KEY NOT NULL, + flags INTEGER NOT NULL, + hdr_from TEXT NOT NULL, + hdr_to TEXT NOT NULL, + hdr_subj TEXT NOT NULL, + hdr_date TEXT NOT NULL + ); + ''') + con.commit() + + self._tags = TagStore(self) + + tags.Tag.register(self) + + def __del__(self): + for con in self._cons.values(): + con.close() + + def get_connection(self): + t = threading.currentThread() + try: + return self._cons[t] + except KeyError: + con = sqlite.connect(self._dbfile) + #con.row_factory = sqlite.Row + self._cons[t] = con + return con + + def _extract_headers(self, msg): + 'we don\'t check for rfc822 compliance here; store whatever the message purports' + frm = msg.get('From', 'undefined') + to = msg.get('To', 'undefined') + subj = msg.get('Subject', 'undefined') + date = msg.get('Date', 'undefined') + return (frm, to, subj, date) + + def add_msg(self, msg, flags=0): + 'msg arg should be email.message.Message instance' + key = self.maildir.add(msg) + (frm, to, subj, date) = self._extract_headers(msg) + con = self.get_connection() + con.execute('INSERT INTO metadata VALUES (?,?,?,?,?,?)', + (key, flags, frm, to, subj, date)) + con.commit() + return key + + def del_msg(self, key): + 'delete from maildir, scrub the db' + self.maildir.remove(key) + con = self.get_connection() + con.executescript(''' + DELETE FROM associations WHERE key=:key; + DELETE FROM metadata WHERE key=?''', (key, key)) + con.commit() + + get_tag = lambda self, uid: self._tags[uid] + + get_msg = lambda self, key: self.maildir.get(msg_key) + + def get_msg_info(self, key): + q = 'SELECT key, flags, hdr_from, hdr_to, hdr_subj, hdr_date FROM metadata WHERE key=?' + con = self.get_connection() + metadata = con.execute(q, (key,)).fetchone() + return MsgInfo(self, *metadata) + + def associated_uids(self, key): + con = self.get_connection() + uids = [res[0] for res in con.execute('SELECT uid FROM associations WHERE key=?', (key,))] + return uids + + def associated_keys(self, uid): + return self._tags[uid].associated_keys() + + def flagged_keys(self, flag, tick=True): + where = 'flags&?' if tick else 'NOT flags&?' + con = self.get_connection() + keys = [res[0] for res in con.execute('SELECT key FROM metadata WHERE %s' % where, (flag,))] + return keys + + def associate(self, uid, key): + self._tags[uid].associate(key) + + def dissociate(self, uid, key): + self._tags[uid].dissociate(key) + + def flag(self, key, flag): + con = self.get_connection() + con.execute('UPDATE metadata SET flags=flags|? WHERE key=?', (flag, key)) + con.commit() + + def unflag(self, key, flag): + con = self.get_connection() + con.execute('UPDATE metadata SET flags=flags&(~?) WHERE key=?', (flag, key)) + con.commit() + + tags = property(lambda self: self._tags) + +class TagStore: + + __contains__ = lambda self: self._tags.__contains__() + + __iter__ = lambda self: self._tags.__iter__() + + __len__ = lambda self: self._tags.__len__() + + def __getitem__(self, key): + for tag in self._tags: + if tag.uid==key: + return tag + else: + return None + + def __init__(self, mailstore): + #self._ms = mailstore + self.get_connection = mailstore.get_connection + + con = self.get_connection() + con.executemany('INSERT OR IGNORE INTO tags (type, uid, label, icon, pos) VALUES (?,?,?,?,?)', + tags.get_defaults()) + con.commit() + + self._tags = [] + self._next_uid = 0 + self._cache_tags() + + def _order_by_pos(self): + self._tags.sort(key=lambda t: t.pos) + + def _cache_tags(self, con=None): + con = self.get_connection() + self._tags = [tags.tag_factory(type, uid, label, icon, pos) + for (type, uid, label, icon, pos) in + con.execute('SELECT type, uid, label, icon, pos FROM tags')] + self._order_by_pos() + max_uid = con.execute('SELECT MAX(uid) FROM tags').fetchone()[0] + self._next_uid = max_uid + 1 + + def add_tag(self, type, label, icon='tag-default', pos=None, query=None): + count = len(self._tags) + if pos is None or pos>count: + pos = count + uid = self._next_uid + tag = tags.tag_factory(type, uid, label, icon, pos, query) + tags.Tag.register(ma) + con = self.get_connection() + con.execute('INSERT INTO tags VALUES(?,?,?,?,?,?,?)', + (uid, type, label, icon, pos, query)) + con.commit() + self._tags.append(tag) + self._order_by_pos() + self._next_uid += 1 + + def del_tag(self, uid): + if not isinstance(self[uid], tags.HardCodedTag): + con = self.get_connection() + con.execute('DELETE FROM tags WHERE uid=?', (uid,)) + con.execute('DELETE FROM associations WHERE uid=?', (uid,)) + con.commit() + self._order_by_pos() + + def get_tag(self, **kwd): + attr, val = kwd.popitem() + for tag in self._tags: + if getattr(tag, attr)==val: + return tag + else: + return None + + def swap_pos(self, uid1, uid2): + tag1 = self[uid1] + tag2 = self.get_tag(uid=uid2) + tmp = tag1.pos + tag1.pos = tag2.pos + tag2.pos = tmp + self._order_by_pos() \ No newline at end of file diff --git a/model/msginfo.py b/model/msginfo.py new file mode 100644 index 0000000..cf963d4 --- /dev/null +++ b/model/msginfo.py @@ -0,0 +1,107 @@ +# Copyright 2009 Shikhar Bhushan +# +# This file is part of the Sweetmail activity for Sugar. +# +# Sweetmail is free software: you can 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. +# +# Sweetmail is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Sweetmail. If not, see . + +from tags import HARDCODED, FLAGS + +import sugar.util +import email.utils +import logging + +class MsgInfo(object): + + def __init__(self, mailstore, key, flags, hdr_from, hdr_to, hdr_subj, hdr_date): + self._ms = mailstore + self._key = key + self._flags = flags + self._hdr_from = hdr_from + self._hdr_to = hdr_to + self._hdr_subj = hdr_subj + self._hdr_date = hdr_date + + def destroy(self): + attrs = (self._ms, + self._key, + self._flags, + self._hdr_from, + self._hdr_subj, + self._hdr_date) + for attr in attrs: + del attr + + def mark(self, flag): + flag = FLAGS.get(flag, None) + if flag is not None: + self._ms.flag(self._key, flag) + self._flags = self._flags|flag + + def unmark(self, flag): + flag = FLAGS.get(flag, None) + if flag is not None: + self._ms.unflag(self._key, flag) + self._flags = self._flags&(~flag) + + def mark_sent(self): + self._ms.unflag(FLAGS['outbound']) + self._ms.flag(self._key, FLAGS['sent']) + + def mark_has_attachment(self): + self._ms.unflag(FLAGS['has_attachment']) + + def _whoify(self, hdr): + if hdr=='undefined': + return _('Unknown') + else: + (name, addr) = email.utils.parseaddr(hdr) + return name if not name=='' else addr + + @property + def msg_id(self): + return self._key + + @property + def who(self): + internal = FLAGS['draft'] | FLAGS['outbound'] | FLAGS['sent'] + if self._flags & internal: + logging.debug('self._hdr_to %s' % self._hdr_to) + return self._whoify(self._hdr_to) + else: + logging.debug('self._hdr_from %s' % self._hdr_from) + return self._whoify(self._hdr_from) + + @property + def what(self): + if self._hdr_subj=='undefined': + return _('No subject') + else: + return self._hdr_subj + + @property + def timestamp(self): + ti = email.utils.parsedate_tz(self._hdr_date) + return email.utils.mktime_tz(ti) + + @property + def when(self): + return sugar.util.timestamp_to_elapsed_string(self.timestamp) + + seen = property(lambda self: bool(self._flags & FLAGS['seen'])) + + unseen = property(lambda self: not self.seen) + + starred = property(lambda self: bool(self._flags & FLAGS['starred'])) + + has_attachment = property(lambda self: bool(self._flags & FLAGS['has_attachment'])) \ No newline at end of file diff --git a/model/tags.py b/model/tags.py new file mode 100644 index 0000000..12ce797 --- /dev/null +++ b/model/tags.py @@ -0,0 +1,292 @@ +# Copyright 2009 Shikhar Bhushan +# +# This file is part of the Sweetmail activity for Sugar. +# +# Sweetmail is free software: you can 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. +# +# Sweetmail is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Sweetmail. If not, see . + +from gettext import gettext as _ + + +# types of tags +_TYPES = {'hardcoded': 0, # as defined in this module + 'vanilla': 1, # your everyday tag + 'smart': 2 # evaluates some query + } + + +FLAGS = {'draft': 1<<1, + 'outbound': 1<<2, + 'sent': 1<<3, + 'seen': 1<<4, + 'starred': 1<<5, + 'replied': 1<<6, + 'forwarded': 1<<7, + 'has_attachment': 1<<8 + } + +# uid's for hardcoded tags +HARDCODED = {'all': 0, # all email (except sent/outbound/draft) + 'sent': 1, # sent email + 'outbound': 2, # email not sent yet but queued + 'drafts': 3, # a draft message + 'unseen': 4, + 'starred': 5, + 'replied': 6, + 'forwarded': 7, + 'has attachment':8, + 'junk': 9, + 'trash': 10, + 'inbox': 11 # received email is tagged this by default + } + +################################################################################ +# BASE CLASSES + +class Tag(object): + + _ms = None + _ts = None + get_connection = None + + @classmethod + def register(cls, mailstore): + cls._ms = mailstore + cls._ts = mailstore.tags + cls.get_connection = mailstore.get_connection + + def __init__(self, uid, label, icon, pos): + self._uid = uid + self._label = label + self._icon = icon + self._pos = pos + + def _update(self, colname, val): + con = self.get_connection() + con.execute('UPDATE tags SET %=? WHERE uid=?', (colname, self._uid)) + con.commit() + setattr(self, '_'+colname, val) + + def _associated_keys(self): + return [r[0] for r in + self.get_connection().execute('SELECT key FROM associations WHERE uid=?', (self._uid,))] + + def _associate(self, key): + tuid, juid = HARDCODED['trash'], HARDCODED['junk'] + con = self.get_connection() + con.execute('DELETE FROM associations WHERE key=? AND (uid=? OR uid=?)', (key, tuid, juid)) + con.execute('INSERT INTO associations VALUES(?,?)', (key, self._uid)) + con.commit() + + def _dissociate(self, key): + con = self.get_connection() + con.execute('DELETE FROM associations WHERE (key=? AND uid=?)', (key, self._uid)) + con.commit() + + def _pass(self, *args): + pass + + def flagged(self, key, flag): + return self.get_connection().execute('SELECT flags&? FROM metadata WHERE key=?', + (flag, key)).fetchone()[0] + + associated_keys = associate = dissociate = _pass + + uid = property(lambda self: self._uid) + + label = property(lambda self: self._label, + lambda self, val: self._update('label', val)) + + icon = property(lambda self: self._icon, + lambda self, val: self._update('icon', val)) + + pos = property(lambda self: self._pos, + lambda self, val: self._update('pos', val)) + +################################################################################ + +class VanillaTag(Tag): + ''' + default behavior + the kind of tag most likely to be used + ''' + + associated_keys = Tag._associated_keys + + associate = Tag._associate + + dissociate = Tag._dissociate + +################################################################################ +#TODO +# a query tag: tags that evaluate some query +# like "unseen lkml who:linus", "all unseen" + +class QueryTag(Tag): + pass + +################################################################################ + +class HardCodedTag(Tag): + + icon = property(lambda self: self._icon) # no changing hardcoded icons + + +class FlagTag(Tag): + ''' + the tick attr specifies whether the FlagTag object interpets the specified flag + as set (True) or not set (False) + ''' + + def __init__(self, flag, tick, *args): + Tag.__init__(self, *args) + self._flag = flag + self._tick = tick + + associated_keys = lambda self: self._ms.flagged_keys(self._flag, self._tick) + + def _associate(self, key): + if self._tick: + self._ms.flag(self, key, self._flag) + else: + self._ms.unflag(self, key, self._flag) + + def _dissociate(self): + if self._tick: + self._ms.unflag(self, key, self._flag) + else: + self._ms.flag(self, key, self._flag) + + +class Inbox(HardCodedTag, VanillaTag): + pass + + +class All(HardCodedTag, FlagTag): + + def __init__(self, *args): + flag = FLAGS['draft'] | FLAGS['outbound'] | FLAGS['sent'] + FlagTag.__init__(self, flag, True, *args) + + +class Replied(HardCodedTag, FlagTag): + + def __init__(self, *args): + FlagTag.__init__(self, FLAGS['replied'], True, *args) + + +class Forwarded(HardCodedTag, FlagTag): + + def __init__(self, *args): + FlagTag.__init__(self, FLAGS['forwarded'], True, *args) + + +class Outbound(HardCodedTag, FlagTag): + + def __init__(self, *args): + FlagTag.__init__(self, FLAGS['outbound'], True, *args) + +class Drafts(HardCodedTag, FlagTag): + + def __init__(self, *args): + FlagTag.__init__(self, FLAGS['draft'], True, *args) + +class Sent(HardCodedTag, FlagTag): + + def __init__(self, *args): + FlagTag.__init__(self, FLAGS['sent'], True, *args) + + +class HasAttachment(HardCodedTag, FlagTag): + + def __init__(self, *args): + FlagTag.__init__(self, FLAGS['has_attachment'], True, *args) + + +class Starred(HardCodedTag, FlagTag): + + def __init__(self, *args): + FlagTag.__init__(self, FLAGS['starred'], True, *args) + + associate = FlagTag._associate + + dissociate = FlagTag._associate + + +class Unseen(HardCodedTag, FlagTag): + + def __init__(self, *args): + FlagTag.__init__(self, FLAGS['seen'], False, *args) + + associate = FlagTag._associate + + dissociate = FlagTag._dissociate + + +class Trash(HardCodedTag): + + associated_keys = HardCodedTag._associated_keys + + def associate(self, key): + ''' + associating with trash tag when not already associated => first mark seen + and unstar + if already associated with trash => delete permanently + ''' + + if self._uid not in self._ms.associated_uids(key): + con = self.get_connection() + con.executescript(''' + DELETE FROM associations WHERE key=?; + INSERT INTO associations VALUES(?,?);''', (key, key, self._uid)) + con.commit() + else: + self._ms.del_msg(key) + +class Junk(Trash): + pass + +################################################################################ + +# uid: (class, localizable name, icon, position) +_DEFAULTS = {0: (All, _('all'), 'tag-all', 5), + 1: (Sent, _('sent'), 'tag-sent', 4), + 2: (Outbound, _('outbound'), 'tag-outbound', 3), + 3: (Drafts, _('drafts'), 'tag-drafts', 2), + 4: (Unseen, _('unseen'), 'tag-unseen', 6), + 5: (Starred, _('starred'), 'tag-starred', 1), + 6: (Replied, _('replied'), 'tag-replied', 8), + 7: (Forwarded, _('forwarded'), 'tag-forwarded', 9), + 8: (HasAttachment, _('has attachment'), 'tag-has-attachment', 7), + 9: (Junk, _('junk'), 'tag-junk', 10), + 10: (Trash, _('trash'), 'tag-trash', 11), + 11: (Inbox, _('inbox'), 'tag-inbox', 0)} + +def get_defaults(): + hct = _TYPES['hardcoded'] + return [(hct, uid, label, icon, pos) + for (uid, (cls, label, icon, pos)) + in zip(_DEFAULTS.keys(), _DEFAULTS.values())] + +################################################################################ + +def tag_factory(type, uid, label, icon, pos, query=None): + if type==_TYPES['hardcoded']: + tag = _DEFAULTS[uid][0](uid, label, icon, pos) + elif type==_TYPES['vanilla']: + tag = VanillaTag(uid, label, icon, pos) + elif type==_TYPES['smart']: + tag = QueryTag(uid, label. icon, pos, query) + else: + tag = None + return tag \ No newline at end of file diff --git a/sweetmail.py b/sweetmail.py new file mode 100755 index 0000000..73cd3c2 --- /dev/null +++ b/sweetmail.py @@ -0,0 +1,109 @@ +import gobject +import gtk +import logging + +from gettext import gettext as _ +from sugar.activity import activity +from sugar.graphics.toolbox import Toolbox +from os.path import join as path_join + +import configure +import contacts +import mailstore +import read +import write + +from bgsrt import BGSRT # background send/receive thread ;p + +class HomeToolbar(activity.ActivityToolbar): + + def __init__(self, mailactivity): + activity.ActivityToolbar.__init__(self, mailactivity) + self.keep.props.visible = False + self.share.props.visible = False + self.canvas = None + +class MailActivityToolbox(activity.ActivityToolbox): + + canvas_by_index = {} + + def __init__(self, mailactivity): + + gtk.gdk.threads_init() + + Toolbox.__init__(self) + + home_toolbar = HomeToolbar(mailactivity) + self.add_toolbar(_('Home'), home_toolbar) + home_toolbar.show() + + read_toolbar = read.ReadToolbar(mailactivity) + self.add_toolbar(_('Read'), read_toolbar) + read_toolbar.show() + + write_toolbar = write.WriteToolbar(mailactivity) + self.add_toolbar(_('Write'), write_toolbar) + write_toolbar.show() + + contacts_toolbar = contacts.ContactsToolbar(mailactivity) + self.add_toolbar(_('Contacts'), contacts_toolbar) + contacts_toolbar.show() + + configure_toolbar = configure.ConfigureToolbar(mailactivity) + self.add_toolbar(_('Configure'), configure_toolbar) + configure_toolbar.show() + + self.toolbars = {0: home_toolbar, + 1: read_toolbar, + 2: write_toolbar, + 3: contacts_toolbar, + 4: configure_toolbar} + + self.connect('current-toolbar-changed', self.__toolbar_changed_cb, mailactivity) + + def __toolbar_changed_cb(self, widget, idx, mailactivity): + toolbar = self.toolbars[idx] + if toolbar.canvas is not None: + canvas = toolbar.canvas(mailactivity) + mailactivity.set_canvas(canvas) + canvas.show_all() + +class MailActivity(activity.Activity): + + def __init__(self, handle): + gtk.gdk.threads_init() + + activity.Activity.__init__(self, handle) + + self._config = configure.Configuration() + + self._ms = mailstore.MailStore(path_join(activity.get_activity_root(), 'data')) + + toolbox = MailActivityToolbox(self) + self.set_toolbox(toolbox) + toolbox.show() + + toolbox.current_toolbar = 1 # default to 'Read' for now + + bgsrt = BGSRT(self) + bgsrt.start() + +# self.connect('visibility-notify-event', self.__visibility_notify_event_cb) +# self.connect('window-state-event', self.__window_state_event_cb) + + # overriding add_alert and remove_alert; want more than one visible + def add_alert(self, alert): + alert.show() + self._alerts.append(alert) + self._vbox.pack_start(alert, False) + self._vbox.reorder_child(alert, 1) + self._vbox.set_child_packing(alert, 0, 0, 1, gtk.PACK_START) + + def remove_alert(self, alert): + if alert in self._alerts: + self._alerts.remove(alert) + self._vbox.remove(alert) + + config = property(lambda self: self._config) + + ms = property(lambda self: self._ms) \ No newline at end of file diff --git a/unrefactored/bgsrt.py b/unrefactored/bgsrt.py new file mode 100644 index 0000000..3db04e3 --- /dev/null +++ b/unrefactored/bgsrt.py @@ -0,0 +1,38 @@ +'Background Send/Receive Thread' + +import email +import email.utils +import gtk +import threading +import time + +from tracker import InboundTracker, OutboundTracker +from tags import FLAGS +from utility import check_online + +class BGSRT(threading.Thread): + + def __init__(self, activity): + threading.Thread.__init__(self) + self._activity = activity + self._config = activity.config + self._ms = activity.ms + + def _send(self): + unsent = self._ms.flagged_keys(FLAGS['outbound']) + if unsent==[]: + return + tracker = OutboundTracker(self._activity) + msgs = [self._ms.get_msg(key) for key in unsent] + self._config.transport_account.send(msgs, tracker) + + def _receive(self): + tracker = InboundTracker(self._activity) + self._config.store_account.retrieve_all(tracker) + + def run(self): + while 1: + if check_online(): + self._send() + self._receive() + time.sleep(self._config.send_receive_every * 60) diff --git a/unrefactored/configure.py b/unrefactored/configure.py new file mode 100644 index 0000000..d56db69 --- /dev/null +++ b/unrefactored/configure.py @@ -0,0 +1,105 @@ +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +from ConfigParser import SafeConfigParser as ConfigParser, NoOptionError +import os + +from sugar.profile import get_nick_name + +import accounts + +class ConfigureCanvas(gtk.Button): + def __init__(self, mailactivity): + gtk.Button.__init__(self, 'CONFIGURE') + +class ConfigureToolbar(gtk.Toolbar): + + def __init__(self, mailactivity): + gtk.Toolbar.__init__(self) + self.mailactivity = mailactivity + self.canvas = ConfigureCanvas + +class Configuration: + + def __init__(self, cfg_file): + self._cfg_file = cfg_file + + if not os.path.exists(self._cfg_file): # create it + open(self._cfg_file, 'w') + + self._cp = ConfigParser() + if not self._cp.read([self._cfg_file]): + logging.error('ConfigParser: error parsing %s', self._cfg_file) + + ### public options ### + + # defaults + self.name = get_nick_name() + self.sync_every = 10 # minutes + self.del_on_retr = True + self.store_account = accounts.DummyStoreAccount() + self.transport_account = accounts.DummyTransportAccount() + + # now parse + self._parse_profile() + self._parse_store() + self._parse_transport() + + def __del__(self): + fp = open(self._cfg_file, 'w') + self._cp.write(fp) + fp.close() + + def _account_dict(self, sec): + kwds = {} + fields = ('host', 'port', 'auth_type', 'username', 'password') + for field in fields: + try: + kwds[field] = self._cp.get(sec, field) + except NoOptionError: + kwds[field] = None + kwds['port'] = int(kwds['port']) + return kwds + + # name, address, sync_every + def _parse_profile(self): + sec = 'sending' + try: + self.name = self._cp.get(sec, 'name') + self.address = self._cp.get(sec, 'address') + except NoOptionError: + pass + + # transport_account + def _parse_store(self): + kwds = _account_dict('store') + try: + kwds['del_on_retr'] = self._cp.getboolean('store', 'delete_on_retrieval') + except NoOptionError: + kwds[field] = True + self._store_account = POPStoreAccount(**kwds) + + # store_account + def _parse_transport(self): + kwds = _account_dict('transport') + try: + kwds['del_on_retr'] = self._cp.getboolean('store', 'delete_on_retrieval') + except NoOptionError: + kwds[field] = True + self._store_account = TransportAccount(**kwds) + + @property + def from_header(self): + from email.utils import formataddr + return formataddr((self.name, self.address)) \ No newline at end of file diff --git a/unrefactored/contacts.py b/unrefactored/contacts.py new file mode 100644 index 0000000..b7a8aaf --- /dev/null +++ b/unrefactored/contacts.py @@ -0,0 +1,12 @@ +import gtk + +class ContactsCanvas(gtk.Button): + def __init__(self, mailactivity): + gtk.Button.__init__(self, 'CONTACTS') + +class ContactsToolbar(gtk.Toolbar): + + def __init__(self, mailactivity): + gtk.Toolbar.__init__(self) + self.mailactivity = mailactivity + self.canvas = ContactsCanvas \ No newline at end of file diff --git a/unrefactored/msgentry.py b/unrefactored/msgentry.py new file mode 100644 index 0000000..baca7b4 --- /dev/null +++ b/unrefactored/msgentry.py @@ -0,0 +1,101 @@ +import hippo +import logging + +from sugar.graphics import style + +from staricon import StarIcon + +class MessageEntry(hippo.CanvasBox): + + _WHO_COL_WIDTH = style.GRID_CELL_SIZE * 4 + _WHEN_COL_WIDTH = style.GRID_CELL_SIZE * 3 + + def __init__(self): + + hippo.CanvasBox.__init__(self, + spacing=style.DEFAULT_SPACING, + padding_top=style.DEFAULT_PADDING, + padding_bottom=style.DEFAULT_PADDING, + padding_left=style.DEFAULT_PADDING * 2, + padding_right=style.DEFAULT_PADDING * 2, + box_height=style.GRID_CELL_SIZE, + orientation=hippo.ORIENTATION_HORIZONTAL) + + self._mobject = None + + self._is_selected = False + + self.star_icon = self._create_star_icon() + self.append(self.star_icon) + + self.what = self._create_what() + self.append(self.what, hippo.PACK_EXPAND) + + self.who = self._create_who() + self.append(self.who) + + self.when = self._create_when() + self.append(self.when) + + def _create_star_icon(self): + star_icon = StarIcon(False) + star_icon.connect('button-release-event', + self.__star_icon_button_release_event_cb) + return star_icon + + def _create_what(self): + what = hippo.CanvasText(text='', + xalign=hippo.ALIGNMENT_START, + font_desc=style.FONT_NORMAL.get_pango_desc(), + size_mode=hippo.CANVAS_SIZE_ELLIPSIZE_END) + return what + + def _create_who(self): + who = hippo.CanvasText(text='', + xalign=hippo.ALIGNMENT_START, + font_desc=style.FONT_NORMAL.get_pango_desc(), + box_width=self._WHO_COL_WIDTH) + return who + + def _create_when(self): + when = hippo.CanvasText(text='', + xalign=hippo.ALIGNMENT_START, + font_desc=style.FONT_NORMAL.get_pango_desc(), + box_width=self._WHEN_COL_WIDTH) + return when + + def _update_color(self): + if self._mobject.unseen: + self.props.background_color = style.COLOR_WHITE.get_int() + else: + self.props.background_color = style.COLOR_WHITE.get_int() + + def __star_icon_button_release_event_cb(self, button, event): + mobject = self._mobject + if mobject.starred: + mobject.unmark('starred') + else: + mobject.mark('starred') + self.star_icon.props.star = mobject.starred + return True + + def set_selected(self, is_selected): + self._is_selected = is_selected + self._update_color() + + def set_mobject(self, mobject): + self._mobject = mobject + self._is_selected = False + + self.star_icon.props.star = mobject.starred + logging.debug(mobject.starred) + self.what.props.text = mobject.what + self.who.props.text = mobject.who + self.when.props.text = mobject.when + + self._update_color() + + mobject = property(lambda self: self._mobject, set_mobject) + + def update_date(self): + self.when.props.text = self._mobject.when diff --git a/unrefactored/msglist.py b/unrefactored/msglist.py new file mode 100644 index 0000000..93a2608 --- /dev/null +++ b/unrefactored/msglist.py @@ -0,0 +1,312 @@ +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import gobject +import gtk +import hippo +import logging +import traceback +import sys + +from gettext import gettext as _ +from sugar import profile +from sugar.graphics import style +from sugar.graphics.icon import CanvasIcon + +import query + +from msgentry import MessageEntry + +UPDATE_INTERVAL = 300000 +NO_MATCHES = _('No matching messages') +NOTHING_TO_SHOW = _('Select a tag') + +class MsgList(gtk.HBox): + + def __init__(self, store): + self._store = store + self._query = {} + self._result_set = None + self._entries = [] + self._page_size = 10 + self._last_value = -1 + self._reflow_sid = 0 + + gtk.HBox.__init__(self) + self.set_flags(gtk.HAS_FOCUS | gtk.CAN_FOCUS) + self.connect('key-press-event', self._key_press_event_cb) + + self._box = hippo.CanvasBox(orientation=hippo.ORIENTATION_VERTICAL, + background_color=style.COLOR_WHITE.get_int()) + self._canvas = hippo.Canvas() + self._canvas.set_root(self._box) + + self.pack_start(self._canvas) + self._canvas.show() + + self._vadjustment = gtk.Adjustment(value=0, lower=0, upper=0, + step_incr=1, page_incr=0, page_size=0) + self._vadjustment.connect('value-changed', self._vadjustment_value_changed_cb) + self._vadjustment.connect('changed', self._vadjustment_changed_cb) + + self._vscrollbar = gtk.VScrollbar(self._vadjustment) + self.pack_end(self._vscrollbar, expand=False, fill=False) + self._vscrollbar.show() + + self.connect('scroll-event', self._scroll_event_cb) + self.connect('destroy', self.__destroy_cb) + + self._fully_obscured = True + self._dirty = False + self._refresh_idle_handler = None + self._update_dates_timer = None + + def __destroy_cb(self, widget): + if self._result_set: + self._result_set.destroy() + + def _vadjustment_changed_cb(self, vadjustment): + logging.debug('_vadjustment_changed_cb:\n \t%r\n \t%r\n \t%r\n \t%r\n \t%r\n' % \ + (vadjustment.props.lower, vadjustment.props.page_increment, + vadjustment.props.page_size, vadjustment.props.step_increment, + vadjustment.props.upper)) + if vadjustment.props.upper > self._page_size: + self._vscrollbar.show() + else: + self._vscrollbar.hide() + + def _vadjustment_value_changed_cb(self, vadjustment): + gobject.idle_add(self._do_scroll) + + def _do_scroll(self, force=False): + import time + t = time.time() + + value = int(self._vadjustment.props.value) + + if value == self._last_value and not force: + return + self._last_value = value + + self._result_set.seek(value) + mobjects = self._result_set.read(self._page_size) + + if self._result_set.length != self._vadjustment.props.upper: + self._vadjustment.props.upper = self._result_set.length + self._vadjustment_changed() + + self._refresh_view(mobjects) + self._dirty = False + + logging.debug('_do_scroll %r %r\n' % (value, (time.time() - t))) + + return False + + def _refresh_view(self, mobjects): + logging.debug('ListView %r' % self) + # no mail to show + if len(mobjects) == 0: + self._show_message(NOTHING_TO_SHOW) + return + # refresh view and create the entries if they don't exist + for i in range(0, self._page_size): + try: + if i < len(mobjects): + if i >= len(self._entries): + entry = self.create_entry() + self._box.append(entry) + self._entries.append(entry) + entry.mobject = mobjects[i] + else: + entry = self._entries[i] + entry.mobject = mobjects[i] + entry.set_visible(True) + elif i < len(self._entries): + entry = self._entries[i] + entry.set_visible(False) + except Exception: + logging.error('Exception while displaying entry:\n' + \ + ''.join(traceback.format_exception(*sys.exc_info()))) + + def create_entry(self): + return MessageEntry() + + def update_with_query(self, query): + logging.debug('update_with_query, page_size = %d' % self._page_size) + self._query = query + if self._page_size > 0: + self.refresh() + + def refresh(self): + if self._result_set: + self._result_set.destroy() + self._result_set = query.find(self._store, self._query) + self._vadjustment.props.upper = self._result_set.length + self._vadjustment.changed() + + self._vadjustment.props.value = min(self._vadjustment.props.value, + self._result_set.length -self._page_size) + + if self._result_set.length == 0: + if self._query.get('query', ''): + self._show_message(NO_MATCH) + else: + self._show_message(NOTHING_TO_SHOW) + else: + self._clear_message() + self._do_scroll(force=True) + + def _scroll_event_cb(self, hbox, event): + if event.direction == gtk.gdk.SCROLL_UP: + if self._vadjustment.props.value > self._vadjustment.props.lower: + self._vadjustment.props.value -= 1 + elif event.direction == gtk.gdk.SCROLL_DOWN: + max_value = self._result_set.length - self._page_size + if self._vadjustment.props.value < max_value: + self._vadjustment.props.value += 1 + + def do_focus(self, direction): + if not self.is_focus(): + self.grab_focus() + return True + return False + + def _key_press_event_cb(self, widget, event): + keyname = gtk.gdk.keyval_name(event.keyval) + + if keyname == 'Up': + if self._vadjustment.props.value > self._vadjustment.props.lower: + self._vadjustment.props.value -= 1 + elif keyname == 'Down': + max_value = self._result_set.length - self._page_size + if self._vadjustment.props.value < max_value: + self._vadjustment.props.value += 1 + elif keyname == 'Page_Up' or keyname == 'KP_Page_Up': + new_position = max(0, self._vadjustment.props.value - self._page_size) + if new_position != self._vadjustment.props.value: + self._vadjustment.props.value = new_position + elif keyname == 'Page_Down' or keyname == 'KP_Page_Down': + new_position = min(self._result_set.length - self._page_size, + self._vadjustment.props.value + self._page_size) + if new_position != self._vadjustment.props.value: + self._vadjustment.props.value = new_position + elif keyname == 'Home' or keyname == 'KP_Home': + new_position = 0 + if new_position != self._vadjustment.props.value: + self._vadjustment.props.value = new_position + elif keyname == 'End' or keyname == 'KP_End': + new_position = max(0, self._result_set.length - self._page_size) + if new_position != self._vadjustment.props.value: + self._vadjustment.props.value = new_position + else: + return False + + return True + + def do_size_allocate(self, allocation): + gtk.HBox.do_size_allocate(self, allocation) + new_page_size = int(allocation.height / style.GRID_CELL_SIZE) + + logging.debug("do_size_allocate: %r" % new_page_size) + + if new_page_size != self._page_size: + self._page_size = new_page_size + self._queue_reflow() + + def _queue_reflow(self): + if not self._reflow_sid: + self._reflow_sid = gobject.idle_add(self._reflow_idle_cb) + + def _reflow_idle_cb(self): + self._box.clear() + self._entries = [] + + self._vadjustment.props.page_size = self._page_size + self._vadjustment.props.page_increment = self._page_size + self._vadjustment_changed() + + if self._result_set is None: + self._result_set = query.find(self._store, self._query) + + max_value = max(0, self._result_set.length - self._page_size) + if self._vadjustment.props.value > max_value: + self._vadjustment.props.value = max_value + else: + self._do_scroll(force=True) + + self._reflow_sid = 0 + + def _show_message(self, message): + box = hippo.CanvasBox(orientation=hippo.ORIENTATION_VERTICAL, + background_color=style.COLOR_WHITE.get_int(), + yalign=hippo.ALIGNMENT_CENTER) + icon = CanvasIcon(size=style.LARGE_ICON_SIZE, + file_name='activity/activity-mail.svg', + stroke_color=style.COLOR_BUTTON_GREY.get_svg(), + fill_color=style.COLOR_TRANSPARENT.get_svg()) + text = hippo.CanvasText(text=message, + xalign=hippo.ALIGNMENT_CENTER, + font_desc=style.FONT_NORMAL.get_pango_desc(), + color=style.COLOR_BUTTON_GREY.get_int()) + + box.append(icon) + box.append(text) + self._canvas.set_root(box) + + def _clear_message(self): + self._canvas.set_root(self._box) + + def update_dates(self): + logging.debug('MessageList.update_dates') + for entry in self._entries: + entry.update_date() + + def _set_dirty(self): + if self._fully_obscured: + self._dirty = True + else: + self._schedule_refresh() + + def _schedule_refresh(self): + if self._refresh_idle_handler is None: + logging.debug('Add refresh idle callback') + self._refresh_idle_handler = gobject.idle_add(self.__refresh_idle_cb) + + def __refresh_idle_cb(self): + self.refresh() + if self._refresh_idle_handler is not None: + logging.debug('Remove refresh idle callback') + gobject.source_remove(self._refresh_idle_handler) + self._refresh_idle_handler = None + return False + + def set_is_visible(self, visible): + logging.debug('canvas_visibility_notify_event_cb %r' % visible) + if visible: + self._fully_obscured = False + if self._dirty: + self._schedule_refresh() + if self._update_dates_timer is None: + logging.debug('Adding date updating timer') + self._update_dates_timer = gobject.timeout_add(UPDATE_INTERVAL, self.__update_dates_timer_cb) + else: + self._fully_obscured = True + if self._update_dates_timer is not None: + logging.debug('Remove date updating timer') + gobject.source_remove(self._update_dates_timer) + self._update_dates_timer = None + + def __update_dates_timer_cb(self): + self.update_dates() + return True diff --git a/unrefactored/pop.py b/unrefactored/pop.py new file mode 100644 index 0000000..fce09f6 --- /dev/null +++ b/unrefactored/pop.py @@ -0,0 +1,75 @@ +import logging + +from gettext import gettext as _ +from poplib import POP3, POP3_SSL + +from accounts import StoreAccount + +_ok = lambda resp: True if resp.startswith('+OK') else False + +class POPError(Exception): pass + +class POPStoreAccount(StoreAccount): + + def __init__(self, host, port, auth_type, username, password, del_on_retr=True): + StoreAccount.__init__(self, host, port, auth_type, username, password, del_on_retr) + + def _connect(self): + cls = POP3_SSL if self._auth_type=='SSL' else POP3 + return cls(self._host, self._port) + + def _authenticate(self, server): + return ( _ok(server.user(self._username)) and _ok(server.pass_(self._password)) ) + + def auth_and_quit(self): + server = self._connect() + if (server is None) or (not self._authenticate(server)): + raise POPError + server.quit() + + def retrieve_all(self, tracker): + + tracker.update(_('Connecting...')) + try: + server = self._connect() + except: + tracker.error(_('Error connecting to %s:%d' % (self._host, self._port))) + return + + tracker.update(_('Authenticating...')) + if not self._authenticate(server): + tracker.error(_('Error authenticating %s' % self._user)) + server.quit() + return + + tracker.update(_('Checking for new mail...')) + (resp, msg_list, octets) = server.list() + if not _ok(resp): + tracker.error(_('Error getting message list.')) + server.quit() + return + num_msgs = len(msg_list) + if num_msgs==0: + tracker.done() + server.quit() + return + + for msg_info in msg_list: + + (num, octets) = msg_info.split() + tracker.update(_('Retrieving message %s of %d...' %(num, num_msgs))) + (resp, lines, octets) = server.retr(num) + if not _ok(resp): + tracker.error(_('Error retrieving message.')) # so?! + server.quit() + return + tracker.dump_msg('\n'.join(lines)) + + if (self._del_on_retr and + not _ok(server.dele(num))): + tracker.error(_('Error deleting message.')) # so?! + server.quit() + return + + tracker.done() + server.quit() diff --git a/unrefactored/query.py b/unrefactored/query.py new file mode 100644 index 0000000..f017e4e --- /dev/null +++ b/unrefactored/query.py @@ -0,0 +1,185 @@ +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import logging + +def search(store, query, offset=0, limit=1000): + keys = store.associated_keys(query['tag']) + total = len(keys) + keys = keys[offset:] + if len(keys) <= limit: + res = [store.get_msg_info(key) for key in keys] + else: + res = [store.get_msg_info(keys[i]) for i in xrange(limit)] + res.sort(key=lambda m: m.timestamp, reverse=True) + return res, total + +def find(store, query): + return ResultSet(store, query) + +class _Cache(object): + + def __init__(self, mobjects=None): + self._array = [] + self._dict = {} + if mobjects is not None: + self.append_all(mobjects) + + def prepend_all(self, mobjects): + for mobject in mobjects[::-1]: + self._array.insert(0, mobject) + self._dict[mobject.msg_id] = mobject + + def append_all(self, mobjects): + for mobject in mobjects: + self._array.append(mobject) + self._dict[mobject.msg_id] = mobject + + def remove_all(self, mobjects): + #mobjects = mobjects[:] + for mobject in mobjects: + obj = self._dict[mobject.msg_id] + self._array.remove(obj) + del self._dict[obj.msg_id] + obj.destroy() + + def __len__(self): + return len(self._array) + + def __getitem__(self, key): + if isinstance(key, basestring): + return self._dict[key] + else: + return self._array[key] + + def destroy(self): + self._destroy_mobjects(self._array) + self._array = [] + self._dict = {} + + def _destroy_mobjects(self, mobjects): + for mobject in mobjects: + mobject.destroy() + +class ResultSet(object): + + _CACHE_LIMIT = 80 + + def __init__(self, store, query): + self._total_count = -1 + self._position = -1 + self._store = store + self._query = query + #self._sorting = sorting + + self._offset = 0 + self._cache = _Cache() + + def destroy(self): + self._cache.destroy() + + def get_length(self): + if self._total_count == -1: + mobjects, self._total_count = search(self._store, + self._query, + limit=ResultSet._CACHE_LIMIT) + self._cache.append_all(mobjects) + self._offset = 0 + return self._total_count + + length = property(get_length) + + def seek(self, position): + self._position = position + + def read(self, max_count): + if max_count * 5 > ResultSet._CACHE_LIMIT: + raise RuntimeError('max_count (%i) too big for ResultSet._CACHE_LIMIT' + ' (%i).' % (max_count, ResultSet._CACHE_LIMIT)) + + if self._position == -1: + self.seek(0) + + if self._position < self._offset: + remaining_forward_entries = 0 + else: + remaining_forward_entries = self._offset + len(self._cache) - \ + self._position + + if self._position > self._offset + len(self._cache): + remaining_backwards_entries = 0 + else: + remaining_backwards_entries = self._position - self._offset + + last_cached_entry = self._offset + len(self._cache) + + if (remaining_forward_entries <= 0 and remaining_backwards_entries <= 0) or \ + max_count > ResultSet._CACHE_LIMIT: + + # Total cache miss: remake it + offset = max(0, self._position - max_count) + logging.debug('remaking cache, offset: %r limit: %r' % (offset, max_count * 2)) + mobjects, self._total_count = search(self._store, + self._query, + offset=offset, + limit=ResultSet._CACHE_LIMIT) + + self._cache.remove_all(self._cache) + self._cache.append_all(mobjects) + self._offset = offset + + elif remaining_forward_entries < 2 * max_count and \ + last_cached_entry < self._total_count: + + # Add one page to the end of cache + logging.debug('appending one more page, offset: %r' % last_cached_entry) + mobjects, self._total_count = search(self._store, + self._query, + offset=last_cached_entry, + limit=max_count) + # update cache + self._cache.append_all(mobjects) + + # apply the cache limit + objects_excess = len(self._cache) - ResultSet._CACHE_LIMIT + if objects_excess > 0: + self._offset += objects_excess + self._cache.remove_all(self._cache[:objects_excess]) + + elif remaining_backwards_entries < 2 * max_count and self._offset > 0: + + # Add one page to the beginning of cache + limit = min(self._offset, max_count) + self._offset = max(0, self._offset - max_count) + + logging.debug('prepending one more page, offset: %r limit: %r' % + (self._offset, limit)) + mobjects, self._total_count = search(self._store, + self._query, + offset=self._offset, + limit=limit) + + # update cache + self._cache.prepend_all(mobjects) + + # apply the cache limit + objects_excess = len(self._cache) - ResultSet._CACHE_LIMIT + if objects_excess > 0: + self._cache.remove_all(self._cache[-objects_excess:]) + else: + logging.debug('cache hit and no need to grow the cache') + + first_pos = self._position - self._offset + last_pos = self._position - self._offset + max_count + return self._cache[first_pos:last_pos] diff --git a/unrefactored/read.py b/unrefactored/read.py new file mode 100644 index 0000000..f25d569 --- /dev/null +++ b/unrefactored/read.py @@ -0,0 +1,64 @@ +import gtk +import logging + +from gettext import gettext as _ +from sugar.graphics.toolbutton import ToolButton + +from taglist import TagList +from msglist import MsgList + +class ReadCanvas(gtk.HBox): + '''temporary playground''' + + def __init__(self, activity): + gtk.HBox.__init__(self) + self.activity = activity + self._ms = activity.ms + + self.taglist = TagList(self._ms.tags) + self.taglist.connect('tag-selected', self.__tag_selected_cb) + self.pack_start(self.taglist, False, False) + self.taglist.show_all() + + self.msglist = MsgList(self._ms) + self.pack_start(self.msglist) + self.msglist.show_all() + self.msglist.set_is_visible(True) + + def __tag_selected_cb(self, widget, uid): + logging.debug('clicked on tag of uid %d' %uid) + self.msglist.update_with_query({'tag':uid}) + +class ReadToolbar(gtk.Toolbar): + ''' + TODO: + * the toolbutton's sensitivity depends on context + ''' + + canvas = ReadCanvas + + def __init__(self, activity): + gtk.Toolbar.__init__(self) + self._activity = activity + self._canvas = None + + self._sendreceive_button = ToolButton('send-and-receive', tooltip=_('Send/receive email')) + self._sendreceive_button.connect('clicked', self._sendreceive_cb) + self.insert(self._sendreceive_button, -1) + + self._reply_button = ToolButton('reply', tooltip=_('Write a reply')) + self._reply_button.connect('clicked', self._reply_msg_cb) + self.insert(self._reply_button, -1) + + self._forward_button = ToolButton('forward', tooltip=_('Forward this message')) + self._forward_button.connect('clicked', self._forward_msg_cb) + self.insert(self._forward_button, -1) + + def _sendreceive_cb(self, *args): + pass + + def _reply_msg_cb(self, *args): + pass + + def _forward_msg_cb(self, *args): + pass diff --git a/unrefactored/setup.py b/unrefactored/setup.py new file mode 100755 index 0000000..00e04a3 --- /dev/null +++ b/unrefactored/setup.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python +from sugar.activity import bundlebuilder +bundlebuilder.start("MailActivity") diff --git a/unrefactored/smtp.py b/unrefactored/smtp.py new file mode 100644 index 0000000..5f6f0bd --- /dev/null +++ b/unrefactored/smtp.py @@ -0,0 +1,90 @@ +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +from gettext import gettext as _ +from smtplib import SMTP + +from accounts import TransportAccount +from pop import POPError +from utility import flatten + +class SMTPTransportAccount(TransportAccount): + + def __init__(self, from_addr, host, port=25, auth_type=None, username=None, password=None, pop_account=None): + TransportAccount.__init__(self, from_addr, host, port, auth_type, username, password) + if auth_type=='POP_BEFORE_SMTP': + self._pop_account = pop_account + + def _connect(self, tracker): + server = SMTP() + if self._auth_type=='POP_BEFORE_SMTP': + tracker.update(_('Authenticating...')) + try: + self._pop_account.auth_and_quit() + except POPError: + tracker.error(_('Error authenticating using POP')) + return None + try: + tracker.update(_('Connecting to server...')) + server.connect(self._host, self._port) + except: + tracker.error(_('Error connecting to %s:%d' % (self._host, self._port))) + return None + if self._auth_type=='SSL': + try: + tracker.update(_('Authenticating...')) + server.ehlo() + server.starttls() + server.ehlo() + server.login(self._username, self._password) + except: + tracker.error(_('Error authenticating %s' % self._username)) + return None + return server + + def __extract_addrs(self, msg): + from email.utils import parseaddr + frm = parseaddr(msg['From']) + to = [split2.strip() for split1 in msg['To'].split(';') for split2 in split1.split(',') if not split2.strip()==''] # eh + return frm, to + + def _deliver(self, server, msg, tracker): + from_addr, to_addrs = self.__extract_addrs(msg) + flattened_msg = flatten(msg) + failures = {} + try: + tracker.update(_('Delivering %s' % msg['Subject'])) + failures = server.sendmail(from_addr, to_addrs, flattened_msg) + except: + tracker.error_delivering(msg) + return None + return failures + + def send(self, msgs, tracker): + server = self._connect(tracker) + if server is None: + tracker.try_later(msgs) + return + for msg in msgs: + failures = self._deliver(server, msg, tracker) + if failures is not None: + if failures=={}: + tracker.sent(msg) + else: + tracker.some_rcpts_failed(msg, failures) + try: + server.quit() + except: + pass + tracker.done() diff --git a/unrefactored/staricon.py b/unrefactored/staricon.py new file mode 100644 index 0000000..2f18c0d --- /dev/null +++ b/unrefactored/staricon.py @@ -0,0 +1,68 @@ +# Copyright (C) 2006, Red Hat, Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import gobject +import hippo +import logging + +from sugar.graphics.icon import CanvasIcon +from sugar.graphics import style +from sugar import profile + +class StarIcon(CanvasIcon): + __gproperties__ = { + 'star' : (bool, None, None, False, + gobject.PARAM_READWRITE) + } + + def __init__(self, star): + CanvasIcon.__init__(self, icon_name='emblem-favorite', + box_width=style.GRID_CELL_SIZE * 3 / 5, + size=style.SMALL_ICON_SIZE) + self.connect('motion-notify-event', self.__motion_notify_event_cb) + + self._star = None + self._set_star(star) + + def _set_star(self, star): + if star == self._star: + return + + self._star = star + if star: + self.props.xo_color = profile.get_color() + else: + self.props.stroke_color = style.COLOR_BUTTON_GREY.get_svg() + self.props.fill_color = style.COLOR_TRANSPARENT.get_svg() + + def do_set_property(self, pspec, value): + if pspec.name == 'star': + self._set_star(value) + else: + CanvasIcon.do_set_property(self, pspec, value) + + def do_get_property(self, pspec): + if pspec.name == 'star': + return self._star + else: + return CanvasIcon.do_get_property(self, pspec) + + def __motion_notify_event_cb(self, icon, event): + if not self._star: + if event.detail == hippo.MOTION_DETAIL_ENTER: + icon.props.fill_color = style.COLOR_BUTTON_GREY.get_svg() + elif event.detail == hippo.MOTION_DETAIL_LEAVE: + icon.props.fill_color = style.COLOR_TRANSPARENT.get_svg() diff --git a/unrefactored/taglist.py b/unrefactored/taglist.py new file mode 100644 index 0000000..39e7d5e --- /dev/null +++ b/unrefactored/taglist.py @@ -0,0 +1,133 @@ +import gobject +import gtk +import hippo +import logging + +from sugar import profile +from sugar.graphics import style +from sugar.graphics.icon import Icon, CanvasIcon +from sugar.graphics.palette import Palette +from sugar.graphics.roundbox import CanvasRoundBox + +class TagPalette(Palette): + + def __init__(self, tag): + tag_icon = Icon(file='icons/'+tag.icon+'.svg', + xo_color=profile.get_color(), + icon_size=gtk.ICON_SIZE_SMALL_TOOLBAR) + Palette.__init__(self, primary_text=tag.label, icon=tag_icon) + self._tag = tag + +class TagIcon(CanvasIcon): + + def __init__(self, tag): + CanvasIcon.__init__(self, size=style.STANDARD_ICON_SIZE/2, cache=True, + file_name='icons/'+tag.icon+'.svg') + self._uncolor() + self._tag = tag + self.connect('hovering-changed', self.__hovering_changed_event_cb) + self.connect('button-release-event', self.__button_release_event_cb) + + def create_palette(self): + palette = TagPalette(self._tag) + #palette.connect('erase-activated', self.__erase_activated_cb) + return palette + + def _color(self): + self.props.xo_color = profile.get_color() + + def _uncolor(self): + self.props.stroke_color = style.COLOR_BUTTON_GREY.get_svg() + self.props.fill_color = style.COLOR_TRANSPARENT.get_svg() + + def __hovering_changed_event_cb(self, icon, hovering): + if hovering: + self._color() + else: + self._uncolor() + + def __button_release_event_cb(self, icon, event): + logging.debug('popping down palette') + self.palette.popdown(immediate=True) + self._uncolor() + +class TagEntry(CanvasRoundBox): + + __gsignals__ = { + 'tag-selected': (gobject.SIGNAL_RUN_FIRST, + gobject.TYPE_NONE, ([str])), + } + + def __init__(self, tag): + CanvasRoundBox.__init__(self, spacing=style.DEFAULT_SPACING/2, + padding_top=style.DEFAULT_PADDING/2, + padding_bottom=style.DEFAULT_PADDING/2, + padding_left=style.DEFAULT_PADDING/2, + padding_right=style.DEFAULT_PADDING/2, + box_height=style.GRID_CELL_SIZE/2, + orientation=hippo.ORIENTATION_HORIZONTAL) + + self._icon = TagIcon(tag) + self.append(self._icon) + + label = hippo.CanvasText(text=tag.label, + xalign=hippo.ALIGNMENT_CENTER, + font_desc=style.FONT_NORMAL.get_pango_desc(), + box_width=style.GRID_CELL_SIZE*2) + self.append(label) + + self._tag = tag + + self.connect('hovering-changed', self.__hovering_changed_event_cb) + self.connect('button-release-event', self.__button_release_event_cb) + + def __hovering_changed_event_cb(self, widget, hovering): + self._icon.emit('hovering-changed', hovering) + + def __button_release_event_cb(self, widget, event): + if event.button==1: + self.emit('tag-selected', self._tag.uid) + else: + self._icon.emit('button-release-event', event) + +class TagList(gtk.VBox): + + __gsignals__ = {'tag-selected': (gobject.SIGNAL_RUN_FIRST, + gobject.TYPE_NONE, + [gobject.TYPE_INT]) + } + + def __tag_selected_cb(self, widget, uid): + self._selected = uid + self.emit('tag-selected', int(uid)) + + def __init__(self, tags): + gtk.VBox.__init__(self) + + # TODO: add buttons for adding / remove a tag, UI elements for new tag + + scrolled_window = gtk.ScrolledWindow() + scrolled_window.set_flags(gtk.HAS_FOCUS|gtk.CAN_FOCUS) + scrolled_window.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) + scrolled_window.set_shadow_type(gtk.SHADOW_NONE) + + self.pack_start(scrolled_window) + scrolled_window.show() + + canvas = hippo.Canvas() + scrolled_window.add_with_viewport(canvas) + #scrolled_window.child.set_shadow_type(gtk.SHADOW_NONE) + canvas.show() + + self._box = hippo.CanvasBox(spacing=style.DEFAULT_SPACING, + padding_top=style.DEFAULT_PADDING*2, + padding_bottom=style.DEFAULT_PADDING*2, + padding_left=style.DEFAULT_PADDING*2, + padding_right=style.DEFAULT_PADDING*2, + background_color = style.COLOR_WHITE.get_int()) + canvas.set_root(self._box) + + for tag in tags: + entry = TagEntry(tag) + entry.connect('tag-selected', self.__tag_selected_cb) + self._box.append(entry) \ No newline at end of file diff --git a/unrefactored/tracker.py b/unrefactored/tracker.py new file mode 100644 index 0000000..7d0828b --- /dev/null +++ b/unrefactored/tracker.py @@ -0,0 +1,129 @@ +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import email +import email.utils +import gtk + +from gettext import gettext as _ +from sugar.graphics.icon import Icon +from sugar.graphics import alert + +from tags import FLAGS, HARDCODED + +def ugly_hack(self, papa, pspec, value): + if pspec.name=='msg': + if self._msg != value: + self._msg = value + self._msg_label.set_markup(self._msg) + else: + papa.do_set_property(self, pspec, value) + +class ProgressAlert(alert.Alert): + + def __init__(self, *args, **kwds): + alert.Alert.__init__(self, *args, **kwds) + icon = Icon(icon_name='emblem-busy') + self.props.icon = icon + icon.show() + + do_set_property = lambda self, pspec, value: ugly_hack(self, alert.Alert, pspec, value) + +class ErrorAlert(alert.NotifyAlert): + + def __init__(self, *args, **kwds): + alert.NotifyAlert.__init__(self, *args, **kwds) + icon = Icon(icon_name='emblem-notification') + self.props.icon = icon + icon.show() + + do_set_property = lambda self, pspec, value: ugly_hack(self, alert.NotifyAlert, pspec, value) + +class ProgressTracker(object): + + def __init__(self, activity, title): + self._activity = activity + self._title = title + self._alert = ProgressAlert() + + self._alert.props.title = title + self._activity.add_alert(self._alert) + + def _remove_alert(self, *args): + gtk.gdk.threads_enter() + self._activity.remove_alert(self._alert) + gtk.gdk.threads_leave() + + def done(self): + self._remove_alert() + + def update(self, msg): + gtk.gdk.threads_enter() + self._alert.props.msg = msg + gtk.gdk.threads_leave() + + def error(self, msg, remove_old=True): + if remove_old: self._remove_alert() + gtk.gdk.threads_enter() + notify(self._activity, self._title, msg) + gtk.gdk.threads_leave() + +class InboundTracker(ProgressTracker): + + def __init__(self, activity): + ProgressTracker.__init__(self, activity, _('Checking email')) + + def dump_msg(self, msg_str): + # TODO setting of FLAGS{'has_attachment'], filtering(!) + msg = email.message_from_string(msg_str) + ms = self._activity.ms + key = ms.add_msg(msg) + # gmail sent emails hack + if email.utils.parseaddr(msg['From'])[1]==self._activity.config.transport_account._from_addr: + ms.flag(key, FLAGS['sent']) + else: + ms.associate(HARDCODED['inbox'], key) + +class OutboundTracker(ProgressTracker): + + def __init__(self, activity): + ProgressTracker.__init__(self, activity, _('Sending email')) + + def _add_and_flag(self, msg, flag): + ms = self._activity.ms + key = ms.add_msg(msg) + ms.flag(key, flag) + + def try_later(self, msgs): + for msg in msgs: + self._add_and_flag(msg, FLAGS['outbound']) + + def error_delivering(self, msg): + self._add_and_flag(msg, FLAGS['draft']) + ProgressTracker.error(self, _('Error delivering %s, message saved as draft.' % msg['Subject']), remove_old=False) + + def some_rcpts_failed(self, msg, who): + msg['To'] = '; '.join(who) + self._add_and_flag(msg, FLAGS['draft']) + ProgressTracker.error(self, _('Error delivering to %s; saved as draft.' % ', '.join(who)), remove_old=False) + + def sent(self, msg): + self._add_and_flag(msg, FLAGS['sent']) + +def notify(activity, title, msg, timeout=5): + alert = ErrorAlert(timeout) + alert.props.title = title + alert.props.msg = msg + activity.add_alert(alert) + alert.connect('response', lambda x,y: activity.remove_alert(alert)) diff --git a/unrefactored/utility.py b/unrefactored/utility.py new file mode 100644 index 0000000..e48c069 --- /dev/null +++ b/unrefactored/utility.py @@ -0,0 +1,62 @@ +import dbus + +def is_address_valid(addr): + """ + Validate e-mail addresses based on lexical rules set forth in RFC 822 + Ported from Recipe 3.9 in Secure Programming Cookbook for C and C++ by + John Viega and Matt Messier (O'Reilly 2003) + """ + + # Mail variables + rfc822_specials = '()<>@,;:\\"[]' + + c = 0 + while c < len(addr): + if addr[c] == '"' and (not c or addr[c - 1] == '.' or addr[c - - 1] == '"'): + c = c + 1 + while c < len(addr): + if addr[c] == '"': break + if addr[c] == '\\' and addr[c + 1] == ' ': + c = c + 2 + continue + if ord(addr[c]) < 32 or ord(addr[c]) >= 127: return 0 + c = c + 1 + else: return 0 + if addr[c] == '@': break + if addr[c] != '.': return 0 + c = c + 1 + continue + if addr[c] == '@': break + if ord(addr[c]) <= 32 or ord(addr[c]) >= 127: return 0 + if addr[c] in rfc822_specials: return 0 + c = c + 1 + if not c or addr[c - 1] == '.': return 0 + + # Next we validate the domain portion (name at domain) + domain = c = c + 1 + if domain >= len(addr): return 0 + count = 0 + while c < len(addr): + if addr[c] == '.': + if c == domain or addr[c - 1] == '.': return 0 + count = count + 1 + if ord(addr[c]) <= 32 or ord(addr[c]) >= 127: return 0 + if addr[c] in rfc822_specials: return 0 + c = c + 1 + + return count >= 1 + +def flatten(msg): + from email.generator import Generator + from cStringIO import StringIO + fp = StringIO() + g = Generator(fp, mangle_from_=False, maxheaderlen=60) + g.flatten(msg) + flattened_msg = fp.getvalue() + return flattened_msg + +def check_online(): + 'returns True if active network connection, False otherwise' + bus = dbus.SystemBus() + proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') + return (proxy.state()==3) diff --git a/unrefactored/write.py b/unrefactored/write.py new file mode 100644 index 0000000..2e3df7b --- /dev/null +++ b/unrefactored/write.py @@ -0,0 +1,124 @@ +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import email.utils +import gtk +import logging +import pango +import thread + +from email.mime.text import MIMEText +from gettext import gettext as _ +from sugar.graphics.toolbutton import ToolButton +from sugar.graphics import style + +from tracker import OutboundTracker, notify +import utility + +class WriteCanvas(gtk.VBox): + + def __init__(self, activity): + gtk.VBox.__init__(self, False, 0) + + self._activity = activity + + self.set_border_width(5) + self.set_spacing(0) + + table = gtk.Table(2, 2) + + to_label = gtk.Label('%s' % _('To')) + to_label.set_use_markup(True) + to_label.set_alignment(0.0, 0.5) + self._to_entry = gtk.Entry() + + subj_label = gtk.Label('%s' % _('Subject')) + subj_label.set_use_markup(True) + subj_label.set_alignment(0.0, 0.5) + self._subj_entry = gtk.Entry() + + padding = style.DEFAULT_PADDING + table.attach(to_label, 0, 1, 0, 1, gtk.FILL, 0, padding, padding) + table.attach(self._to_entry, 1, 2, 0, 1, gtk.EXPAND|gtk.FILL, 0, padding, padding) + table.attach(subj_label, 0, 1, 1, 2, gtk.FILL, 0, padding, padding) + table.attach(self._subj_entry, 1, 2, 1, 2, gtk.EXPAND|gtk.FILL, 0, padding, padding) + + self.pack_start(table, False, False, 0) + + scrolled = gtk.ScrolledWindow() + scrolled.set_shadow_type(gtk.SHADOW_IN) + + self._textview = gtk.TextView() + for prop in ('left_margin', 'right_margin', 'pixels_above_lines', 'pixels_below_lines'): + setattr(self._textview.props, prop, style.DEFAULT_SPACING) + self._textview.set_wrap_mode(gtk.WRAP_WORD) + + scrolled.add_with_viewport(self._textview) + + self.pack_start(scrolled, True, True, 0) + + def make_msg(self): # egh + + to = self._to_entry.get_text() + subj = self._subj_entry.get_text() + buf = self._textview.get_buffer() + start, end = buf.get_bounds() + body = buf.get_text(start, end) + + msg = MIMEText(body) + msg['From'] = self._activity.config.from_hdr + msg['To'] = to + msg['Subject'] = subj + msg['Date'] = email.utils.formatdate() + msg['Message-ID'] = email.utils.make_msgid() + return msg + +class WriteToolbar(gtk.Toolbar): + + canvas = WriteCanvas + + def __init__(self, activity): + gtk.Toolbar.__init__(self) + self._activity = activity + + self._send_button = ToolButton('send-email', tooltip=_('Send email')) + self._send_button.connect('clicked', self.__send_email_cb) + self.insert(self._send_button, -1) + + self._attach_button = ToolButton('add-attachment', tooltip=_('Add attachment')) + self._attach_button.connect('clicked', self.__add_attachment_cb) + self.insert(self._attach_button, -1) + + self.show_all() + + + def __send_email_cb(self, *args): + msg = self._activity.canvas.make_msg() + if utility.check_online(): + func = self._activity.config.transport_account.send + args = ([msg], OutboundTracker(self._activity)) + thread.start_new_thread(func, args) + else: + self._keep_as_outbound(msg) + self._activity.toolbox.current_toolbar = 1 # egh + + def __add_attachment_cb(self, *args): + pass + +def keep_as_outbound(self, msg): + ms = self._activity.ms + key = ms.add_msg(msg) + ms.flag(key, FLAGS['outbound']) + notify(self._activity, _("%s kept as outbound" % msg['Subject']), + _('No network connection')) \ No newline at end of file -- cgit v0.9.1