commit 614d80e479b85aea21aec96ea62ddf5e106ffb69 Author: Mauricio Baeza Date: Mon Sep 9 22:42:38 2019 -0500 Initial version diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..59fa655 --- /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. + + empresa-libre + Copyright (C) 2016 Mauricio Baeza + + This program is free software: you can 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: + + empresa-libre Copyright (C) 2016 Mauricio Baeza + 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/README.md b/README.md new file mode 100644 index 0000000..1970a9a --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +ZAZ BarCode + +Extension for insert barcode in LibreOffice documents + +Barcodes provided + +* code39 +* code128 +* ean +* ean13 +* ean8 +* gs1 +* gtin +* isbn +* isbn10 +* isbn13 +* issn +* jan +* pzn +* upc +* upca +* qrcode + + +Thanks! + +https://gitlab.com/mauriciobaeza/zaz + +https://github.com/WhyNotHugo/python-barcode + +https://github.com/lincolnloop/python-qrcode + + +This extension have a cost of maintenance of 1 euro every year. + +BCH: `1RPLWHJW34p7pMQV1ft4x7eWhAYw69Dsb` + +BTC: `3Fe4JuADrAK8Qs7GDAxbSXR8E54avwZJLW` diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/__pycache__/conf.cpython-37.pyc b/__pycache__/conf.cpython-37.pyc new file mode 100644 index 0000000..dcd4199 Binary files /dev/null and b/__pycache__/conf.cpython-37.pyc differ diff --git a/__pycache__/easymacro.cpython-37.pyc b/__pycache__/easymacro.cpython-37.pyc new file mode 100644 index 0000000..bd877f2 Binary files /dev/null and b/__pycache__/easymacro.cpython-37.pyc differ diff --git a/conf.py b/conf.py new file mode 100644 index 0000000..fec152c --- /dev/null +++ b/conf.py @@ -0,0 +1,672 @@ +#!/usr/bin/env python3 + +# ~ This file is part of ZAZ. + +# ~ ZAZ is free software: you can 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. + +# ~ ZAZ is distributed in the hope that it will be useful, +# ~ but WITHOUT ANY WARRANTY; without even the implied warranty of +# ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# ~ GNU General Public License for more details. + +# ~ You should have received a copy of the GNU General Public License +# ~ along with ZAZ. If not, see . + + +import logging + + +# ~ Type extension: +# ~ 1 = normal extension +# ~ 2 = new component +# ~ 3 = Calc addin +TYPE_EXTENSION = 1 + +# ~ https://semver.org/ +VERSION = '0.1.0' + +# ~ Your great extension name, not used spaces +NAME = 'ZAZBarCode' + +# ~ Should be unique, used URL inverse +ID = 'net.elmau.zaz.BarCode' + +PUBLISHER = { + 'en': {'text': 'El Mau', 'link': 'https://gitlab.com/mauriciobaeza'}, + 'es': {'text': 'El Mau', 'link': 'https://gitlab.com/mauriciobaeza'}, +} + +# ~ Name in this folder for copy +ICON = 'images/logo.png' +# ~ Name inside extensions +ICON_EXT = f'{NAME.lower()}.png' + +# ~ For example +# ~ DEPENDENCIES_MINIMAL = '6.0' +DEPENDENCIES_MINIMAL = '' + +# ~ Change for you favorite license +LICENSE_EN = f"""This file is part of {NAME}. + + {NAME} is free software: you can 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. + + {NAME} is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with {NAME}. If not, see . +""" +LICENSE_ES = LICENSE_EN + + +INFO = { + 'en': { + 'display_name': 'ZAZ Bar Code', + 'description': 'Generate and insert barcode in documents', + 'license': LICENSE_EN, + }, + 'es': { + 'display_name': 'ZAZ Códigos de Barras', + 'description': 'Genera e inserta codigos de barras en documentos', + 'license': LICENSE_ES, + }, +} + + +CONTEXT = { + 'calc': 'com.sun.star.sheet.SpreadsheetDocument', + 'writer': 'com.sun.star.text.TextDocument', + 'impress': 'com.sun.star.presentation.PresentationDocument', + 'draw': 'com.sun.star.drawing.DrawingDocument', + 'base': 'com.sun.star.sdb.OfficeDatabaseDocument', + 'math': 'com.sun.star.formula.FormulaProperties', + 'basic': 'com.sun.star.script.BasicIDE', +} + + +# ~ Menus, only for TYPE_EXTENSION = 1 +# ~ Parent can be: AddonMenu or OfficeMenuBar +# ~ For icons con name: NAME_16.bmp, used only NAME +# ~ PARENT = 'AddonMenu' +# ~ MENU_MAIN = '' +PARENT = 'OfficeMenuBar' +MENU_MAIN = { + 'en': 'ZAZ BarCode', + 'es': 'ZAZ BarCode', +} +MENUS = ( + { + 'title': {'en': 'Insert BarCode', 'es': 'Insertar Código'}, + 'argument': 'ask', + 'context': 'calc,writer,impress,draw', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert CODE39', 'es': 'Insertar CODE39'}, + 'argument': 'code39', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert CODE128', 'es': 'Insertar CODE128'}, + 'argument': 'code128', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert EAN', 'es': 'Insertar EAN'}, + 'argument': 'ean', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert EAN8', 'es': 'Insertar EAN8'}, + 'argument': 'ean8', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert EAN13', 'es': 'Insertar EAN13'}, + 'argument': 'ean13', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert GS1', 'es': 'Insertar GS1'}, + 'argument': 'gs1', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert GTIN', 'es': 'Insertar GTIN'}, + 'argument': 'gtin', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert ISBN', 'es': 'Insertar ISBN'}, + 'argument': 'isbn', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert ISBN10', 'es': 'Insertar ISBN10'}, + 'argument': 'isbn10', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert ISBN13', 'es': 'Insertar ISBN13'}, + 'argument': 'isbn13', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert ISSN', 'es': 'Insertar ISSN'}, + 'argument': 'issn', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert JAN', 'es': 'Insertar JAN'}, + 'argument': 'jan', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert PZN', 'es': 'Insertar PZN'}, + 'argument': 'pzn', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert UPC', 'es': 'Insertar UPC'}, + 'argument': 'upc', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert UPCA', 'es': 'Insertar UPCA'}, + 'argument': 'upca', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, + { + 'title': {'en': 'Insert QRCODE', 'es': 'Insertar QRCODE'}, + 'argument': 'qrcode', + 'context': 'calc,writer', + 'icon': 'barcode', + 'toolbar': False, + }, +) + + +# ~ Functions, only for TYPE_EXTENSION = 3 +FUNCTIONS = { + 'test': { + 'displayname': {'en': 'test', 'es': 'prueba'}, + 'description': {'en': 'My test', 'es': 'Mi prueba'}, + 'parameters': { + 'value': { + 'displayname': {'en': 'value', 'es': 'valor'}, + 'description': {'en': 'The value', 'es': 'El valor'}, + }, + }, + }, +} +# ~ FUNCTIONS = {} + +EXTENSION = { + 'version': VERSION, + 'name': NAME, + 'id': ID, + 'icon': (ICON, ICON_EXT), +} + + +# ~ If used more libraries set python path in True and copy inside +# ~ If used easymacro pythonpath always is True +DIRS = { + 'meta': 'META-INF', + 'source': 'source', + 'description': 'description', + 'images': 'images', + 'registration': 'registration', + 'files': 'files', + 'pythonpath': False, +} + + +FILES = { + 'oxt': f'{NAME}_v{VERSION}.oxt', + 'py': f'{NAME}.py', + 'ext_desc': 'desc_{}.txt', + 'manifest': 'manifest.xml', + 'description': 'description.xml', + 'idl': f'X{NAME}.idl', + 'addons': 'Addons.xcu', + 'urd': f'X{NAME}.urd', + 'rdb': f'X{NAME}.rdb', + 'update': f'{NAME.lower()}.update.xml', + 'addin': 'CalcAddIn.xcu', + 'easymacro': True, +} + + +# ~ URLs for update for example +# ~ URL_XML_UPDATE = 'https://gitlab.com/USER/PROYECT/raw/BRANCH/FOLDERs/FILE_NAME' +URL_XML_UPDATE = '' +URL_OXT = '' + + +FILE_TEST = '/home/mau/test/test.ods' +PATHS = { + 'idlc': '/usr/lib/libreoffice/sdk/bin/idlc', + 'include': '/usr/share/idl/libreoffice', + 'regmerge': '/usr/lib/libreoffice/program/regmerge', + 'soffice': ('soffice', '--calc', FILE_TEST), + 'install': ('unopkg', 'add', '-v', '-f', '-s'), +} + + +SERVICES = { + 'job': "('com.sun.star.task.Job',)", + 'addin': "('com.sun.star.sheet.AddIn',)", +} + + +FORMAT = '%(asctime)s - %(levelname)s - %(message)s' +DATE = '%d/%m/%Y %H:%M:%S' +LEVEL_ERROR = logging.getLevelName(logging.ERROR) +LEVEL_INFO = logging.getLevelName(logging.INFO) +logging.addLevelName(logging.ERROR, f'\033[1;41m{LEVEL_ERROR}\033[1;0m') +logging.addLevelName(logging.INFO, f'\x1b[32m{LEVEL_INFO}\033[1;0m') +logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt=DATE) +log = logging.getLogger(NAME) + + +def _methods(): + template = """ def {0}(self, {1}): + print({1}) + return 'ok'\n""" + functions = '' + for k, v in FUNCTIONS.items(): + args = ','.join(v['parameters'].keys()) + functions += template.format(k, args) + return functions + + +SRV = SERVICES['job'] +XSRV = 'XJobExecutor' +SRV_IMPORT = f'from com.sun.star.task import {XSRV}' +METHODS = """ def trigger(self, args='pyUNO'): + print('Hello World', args) + return\n""" + +if TYPE_EXTENSION > 1: + MENUS = () + XSRV = f'X{NAME}' + SRV_IMPORT = f'from {ID} import {XSRV}' +if TYPE_EXTENSION == 2: + SRV = f"('{ID}',)" + METHODS = """ def test(self, args='pyUNO'): + print('Hello World', args) + return\n""" +elif TYPE_EXTENSION == 3: + SRV = SERVICES['addin'] + METHODS = _methods() + + +FILE_PY = f"""import uno +import unohelper +{SRV_IMPORT} + + +ID_EXTENSION = '{ID}' +SERVICE = {SRV} + + +class {NAME}(unohelper.Base, {XSRV}): + + def __init__(self, ctx): + self.ctx = ctx + +{METHODS} + +g_ImplementationHelper = unohelper.ImplementationHelper() +g_ImplementationHelper.addImplementation({NAME}, ID_EXTENSION, SERVICE) +""" + + +tmp = ' {}' +node = [tmp.format(k, v['display_name']) for k, v in INFO.items()] +NODE_DISPLAY_NAME = '\n'.join(node) + +tmp = ' ' +node = [tmp.format(k) for k, v in INFO.items()] +NODE_EXTENSION_DESCRIPTION = '\n'.join(node) + +NODE_ICON = '' +if ICON: + NODE_ICON = f' ' + +NODE_PUBLISHER = '' +if PUBLISHER: + tmp = ' {}' + node = [tmp.format(v['link'], k, v['text']) for k, v in PUBLISHER.items()] + NODE_PUBLISHER = '\n'.join(node) + +NODE_DEPENDENCIES_MINIMAL = '' +if DEPENDENCIES_MINIMAL: + NODE_DEPENDENCIES_MINIMAL = f"""\n + + """ + +tmp = ' ' +node = [tmp.format(DIRS['registration'], k) for k in INFO.keys()] +NODE_LICENSE = '\n'.join(node) + +NODE_UPDATE = '' +if URL_XML_UPDATE: + NODE_UPDATE = f""" + + + """ + +FILE_DESCRIPTION = f""" + + + + +{NODE_DISPLAY_NAME} + + +{NODE_EXTENSION_DESCRIPTION} + + +{NODE_ICON} + + +{NODE_PUBLISHER} + + + +{NODE_LICENSE} + + {NODE_DEPENDENCIES_MINIMAL}{NODE_UPDATE} + +""" + +NODE_MENU = """ + +{titles} + + + service:{id}?{argument} + + + _self + + + {context} + + + %origin%/{folder}/{icon} + + """ + +opt = 'fuse' +if PARENT == 'OfficeMenuBar': + opt = 'replace' + + +def _get_context(args): + c = [] + for v in args.split(','): + c.append(CONTEXT[v]) + return ','.join(c) + + +menus = [] +toolbar = [] +tmp = ' {}' +for i, m in enumerate(MENUS): + titles = [tmp.format(k, v) for k, v in m['title'].items()] + values = { + 'id': ID, + 'index': i+101, + 'opt': opt, + 'titles': '\n'.join(titles), + 'argument': m['argument'], + 'context': _get_context(m['context']), + 'folder': DIRS['images'], + 'icon': m['icon'], + } + menus.append(NODE_MENU.format(**values)) + if m['toolbar']: + values['index'] = f't{i+1}' + toolbar.append(NODE_MENU.format(**values)) + +NODE_TOOLBAR = '' +if PARENT == 'AddonMenu': + NODE_MENUS = '\n'.join(menus) +else: + tmp = ' {}' + titles = '\n'.join([tmp.format(k, v) for k, v in MENU_MAIN.items()]) + SUBMENUS = '\n ' + '\n'.join(menus) + '\n ' + NODE_MENUS = f""" + +{titles} + + + _self + + {SUBMENUS} + """ + + if toolbar: + node_toolbars = '\n'.join(toolbar) + NODE_TOOLBAR = f""" + +{node_toolbars} + + """ + +FILE_ADDONS = f""" + + + +{NODE_MENUS} + +{NODE_TOOLBAR} + + +""" + + +NODE_ADDONS = '\n ' +if TYPE_EXTENSION > 1: + NODE_ADDONS = f'\n ' +if TYPE_EXTENSION == 3: + NODE_ADDONS += '\n ' + +FILE_MANIFEST = f""" + + {NODE_ADDONS} + +""" + + +FILE_UPDATE = '' +if URL_XML_UPDATE: + FILE_UPDATE = f""" + + + + + + + + + + + +""" + + +def _functions(): + a = '[in] any {}' + t = ' any {}({});' + f = '' + for k, v in FUNCTIONS.items(): + args = ','.join([a.format(k) for k, v in v['parameters'].items()]) + f += t.format(k, args) + return f + + +FILE_IDL = '' +if TYPE_EXTENSION > 1: + id_ext = ID.replace('.', '_') + interface = f'X{NAME}' + module = '' + for i, P in enumerate(ID.split('.')): + module += f'module {P} {{ ' + close_module = '}; ' * (i + 1) + functions = ' void test([in] any argument);' + if TYPE_EXTENSION == 3: + functions = _functions() + + FILE_IDL = f"""#ifndef __{id_ext}_idl__ +#define __{id_ext}_idl__ + +#include + +{module} + + interface {interface} : com::sun::star::uno::XInterface + {{ +{functions} + }}; + + service {P} {{ + interface {interface}; + }}; + +{close_module} +#endif +""" + + +def _parameters(args): + NODE = """ + +{displayname} + + +{description} + + """ + line = '{}{}' + node = '' + for k, v in args.items(): + displayname = '\n'.join( + [line.format(' ' * 16, k, v) for k, v in v['displayname'].items()]) + description = '\n'.join( + [line.format(' ' * 16, k, v) for k, v in v['description'].items()]) + values = { + 'name': k, + 'displayname': displayname, + 'description': description, + } + node += NODE.format(**values) + return node + + +NODE_FUNCTIONS = '' +if TYPE_EXTENSION == 3: + tmp = '{}{}' + NODE_FUNCTION = """ + +{displayname} + + +{description} + + + Add-In + + + AutoAddIn.{name} + + +{parameters} + + """ + + for k, v in FUNCTIONS.items(): + displayname = '\n'.join( + [tmp.format(' ' * 12, k, v) for k, v in v['displayname'].items()]) + description = '\n'.join( + [tmp.format(' ' * 12, k, v) for k, v in v['description'].items()]) + parameters = _parameters(v['parameters']) + values = { + 'name': k, + 'displayname': displayname, + 'description': description, + 'parameters': parameters, + } + NODE_FUNCTIONS += NODE_FUNCTION.format(**values) + + +FILE_ADDIN = f""" + + + + +{NODE_FUNCTIONS} + + + +""" + + +DATA = { + 'py': FILE_PY, + 'manifest': FILE_MANIFEST, + 'description': FILE_DESCRIPTION, + 'addons': FILE_ADDONS, + 'update': FILE_UPDATE, + 'idl': FILE_IDL, + 'addin': FILE_ADDIN, +} + + +# ~ LICENSE_ACCEPT_BY = 'admin' # or admin +# ~ LICENSE_SUPPRESS_ON_UPDATE = True diff --git a/easymacro.py b/easymacro.py new file mode 100644 index 0000000..76de6cf --- /dev/null +++ b/easymacro.py @@ -0,0 +1,1000 @@ +#!/usr/bin/env python3 + +# == Rapid Develop Macros in LibreOffice == + +# ~ This file is part of ZAZ. + +# ~ ZAZ is free software: you can 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. + +# ~ ZAZ is distributed in the hope that it will be useful, +# ~ but WITHOUT ANY WARRANTY; without even the implied warranty of +# ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# ~ GNU General Public License for more details. + +# ~ You should have received a copy of the GNU General Public License +# ~ along with ZAZ. If not, see . + + +import getpass +import logging +import os +import platform +import sys +import tempfile +import threading +import time +from functools import wraps + +import uno +import unohelper +from com.sun.star.beans import PropertyValue +from com.sun.star.awt import MessageBoxButtons as MSG_BUTTONS +from com.sun.star.awt.MessageBoxResults import YES +from com.sun.star.awt.PosSize import POSSIZE, SIZE +from com.sun.star.awt import Size, Point +from com.sun.star.table.CellContentType import EMPTY, VALUE, TEXT, FORMULA + +from com.sun.star.text.TextContentAnchorType import AS_CHARACTER + +from com.sun.star.lang import XEventListener +from com.sun.star.awt import XActionListener +from com.sun.star.awt import XMouseListener + + +FILE_NAME_DEBUG = 'debug.log' +MSG_LANG = { + 'es': { + 'OK': 'Aceptar', + 'Cancel': 'Cancelar', + } +} + +FORMAT = '%(asctime)s - %(levelname)s - %(message)s' +DATE = '%d/%m/%Y %H:%M:%S' +LEVEL_ERROR = logging.getLevelName(logging.ERROR) +LEVEL_DEBUG = logging.getLevelName(logging.DEBUG) +LEVEL_INFO = logging.getLevelName(logging.INFO) +logging.addLevelName(logging.ERROR, f'\033[1;41m{LEVEL_ERROR}\033[1;0m') +logging.addLevelName(logging.DEBUG, f'\x1b[33m{LEVEL_DEBUG}\033[1;0m') +logging.addLevelName(logging.INFO, f'\x1b[32m{LEVEL_INFO}\033[1;0m') +logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt=DATE) +log = logging.getLogger(__name__) + + +OBJ_CELL = 'ScCellObj' +OBJ_RANGE = 'ScCellRangeObj' +OBJ_RANGES = 'ScCellRangesObj' +OBJ_TYPE_RANGES = (OBJ_CELL, OBJ_RANGE, OBJ_RANGES) + +CTX = uno.getComponentContext() +SM = CTX.getServiceManager() + + +def create_instance(name, with_context=False): + if with_context: + instance = SM.createInstanceWithContext(name, CTX) + else: + instance = SM.createInstance(name) + return instance + + +def _get_config(key, node_name): + name = 'com.sun.star.configuration.ConfigurationProvider' + service = 'com.sun.star.configuration.ConfigurationAccess' + cp = create_instance(name, True) + node = PropertyValue(Name='nodepath', Value=node_name) + try: + ca = cp.createInstanceWithArguments(service, (node,)) + if ca and (ca.hasByName(key)): + data = ca.getPropertyValue(key) + return data + except Exception as e: + log.error(e) + return '' + + +OS = sys.platform +USER = getpass.getuser() +PC = platform.node() + +LANGUAGE = _get_config('ooLocale', 'org.openoffice.Setup/L10N/') +NAME = TITLE = _get_config('ooName', 'org.openoffice.Setup/Product') +VERSION = _get_config('ooSetupVersion', 'org.openoffice.Setup/Product') +# ~ DESKTOP = create_instance('com.sun.star.frame.Desktop', True) + +INFO_DEBUG = '{}\n\n{}\n\n{}'.format( + sys.version, platform.platform(), '\n'.join(sys.path)) + + +def mri(obj): + m = create_instance('mytools.Mri') + if m is None: + msg = 'Extension MRI not found' + error(msg) + return + + m.inspect(obj) + return + + +def debug(info): + log.debug(info) + return + + +def error(info): + log.error(info) + return + + +def catch_exception(f): + @wraps(f) + def func(*args, **kwargs): + try: + return f(*args, **kwargs) + except Exception as e: + log.error(f.__name__, exc_info=True) + return func + + +def run_in_thread(fn): + def run(*k, **kw): + t = threading.Thread(target=fn, args=k, kwargs=kw) + t.start() + return t + return run + + +def _(msg): + L = LANGUAGE.split('-')[0] + if L == 'en': + return msg + + if not L in MSG_LANG: + return msg + + return MSG_LANG[L][msg] + + +def msgbox(message, title=TITLE, buttons=MSG_BUTTONS.BUTTONS_OK, type_msg='infobox'): + """ Create message box + type_msg: infobox, warningbox, errorbox, querybox, messbox + http://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1awt_1_1XMessageBoxFactory.html + """ + toolkit = create_instance('com.sun.star.awt.Toolkit') + parent = toolkit.getDesktopWindow() + mb = toolkit.createMessageBox(parent, type_msg, buttons, title, str(message)) + return mb.execute() + + +def question(message, title=TITLE): + res = msgbox(message, title, MSG_BUTTONS.BUTTONS_YES_NO, 'querybox') + return res == YES + + +def warning(message, title=TITLE): + return msgbox(message, title, type_msg='warningbox') + + +def errorbox(message, title=TITLE): + return msgbox(message, title, type_msg='errorbox') + + +def get_desktop(): + return create_instance('com.sun.star.frame.Desktop', True) + + +def get_temp_file(): + return tempfile.NamedTemporaryFile() + + +def _path_url(path): + if path.startswith('file://'): + return path + return uno.systemPathToFileUrl(path) + + +def _path_system(path): + if path.startswith('file://'): + return os.path.abspath(uno.fileUrlToSystemPath(path)) + return path + + +def get_type_doc(obj): + services = { + 'calc': 'com.sun.star.sheet.SpreadsheetDocument', + 'writer': 'com.sun.star.text.TextDocument', + 'impress': 'com.sun.star.presentation.PresentationDocument', + 'draw': 'com.sun.star.drawing.DrawingDocument', + 'base': 'com.sun.star.sdb.OfficeDatabaseDocument', + 'math': 'com.sun.star.formula.FormulaProperties', + 'basic': 'com.sun.star.script.BasicIDE', + } + for k, v in services.items(): + if obj.supportsService(v): + return k + return '' + + +# ~ Custom classes + + +class LODocument(object): + + def __init__(self, obj): + self._obj = obj + self._init_values() + + def _init_values(self): + self._type_doc = get_type_doc(self.obj) + self._cc = self.obj.getCurrentController() + return + + @property + def obj(self): + return self._obj + + @property + def type(self): + return self._type_doc + + @property + def title(self): + return self.obj.getTitle() + + @property + def is_saved(self): + return self.obj.hasLocation() + + @property + def is_modified(self): + return self.obj.isModified() + + @property + def is_read_only(self): + return self.obj.isReadOnly() + + @property + def path(self): + return _path_system(self.obj.getURL()) + + @property + def visible(self): + w = self._cc.getFrame().getContainerWindow() + return w.Visible + @visible.setter + def visible(self, value): + w = self._cc.getFrame().getContainerWindow() + w.setVisible(value) + + @property + def zoom(self): + return self._cc.ZoomValue + @zoom.setter + def zoom(self, value): + self._cc.ZoomValue = value + + def create_instance(self, name): + obj = self.obj.createInstance(name) + return obj + + +class LOCalc(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + @property + def obj(self): + return self._obj + + @property + def active(self): + return LOCalcSheet(self._cc.getActiveSheet(), self) + + @property + def selection(self): + sel = self.obj.getCurrentSelection() + if sel.ImplementationName in OBJ_TYPE_RANGES: + sel = LOCellRange(sel, self) + return sel + + def get_cell(self, index=None): + """ + index is str 'A1' + index is tuple (row, col) + """ + if index is None: + cell = self.selection.first + else: + cell = LOCellRange(self.active[index].obj, self) + return cell + + # ~ def create_instance(self, name): + # ~ obj = self.obj.createInstance(name) + # ~ return obj + + +class LOCalcSheet(object): + + def __init__(self, obj, doc): + self._obj = obj + self._doc = doc + self._init_values() + + def __getitem__(self, index): + return LOCellRange(self.obj[index], self.doc) + + def _init_values(self): + return + + @property + def obj(self): + return self._obj + + @property + def doc(self): + return self._doc + + +class LOWriter(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + @property + def obj(self): + return self._obj + + @property + def string(self): + return self._obj.getText().String + + @property + def text(self): + return self._obj.getText() + + @property + def cursor(self): + return self.text.createTextCursor() + + @property + def selection(self): + sel = self._cc.getSelection() + return LOTextRange(sel[0]) + + def insert_content(self, cursor, data, replace=False): + self.text.insertTextContent(cursor, data, replace) + return + + # ~ tt = doc.createInstance('com.sun.star.text.TextTable') + # ~ tt.initialize(5, 2) + + # ~ f = doc.createInstance('com.sun.star.text.TextFrame') + # ~ f.setSize(Size(10000, 500)) + + def insert_image(self, path, **kwargs): + cursor = kwargs.get('cursor', self.selection.cursor.getEnd()) + w = kwargs.get('width', 1000) + h = kwargs.get('Height', 1000) + image = self.create_instance('com.sun.star.text.GraphicObject') + image.GraphicURL = _path_url(path) + image.AnchorType = AS_CHARACTER + image.Width = w + image.Height = h + self.insert_content(cursor, image) + return + + +class LOTextRange(object): + + def __init__(self, obj): + self._obj = obj + + @property + def obj(self): + return self._obj + + @property + def string(self): + return self.obj.String + + @property + def text(self): + return self.obj.getText() + + @property + def cursor(self): + return self.text.createTextCursorByRange(self.obj) + + +class LOBase(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + +class LODrawImpress(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + @property + def draw_page(self): + return self._cc.getCurrentPage() + + @catch_exception + def insert_image(self, path, **kwargs): + w = kwargs.get('width', 3000) + h = kwargs.get('Height', 1000) + x = kwargs.get('X', 1000) + y = kwargs.get('Y', 1000) + + image = self.create_instance('com.sun.star.drawing.GraphicObjectShape') + image.GraphicURL = _path_url(path) + image.Size = Size(w, h) + image.Position = Point(x, y) + self.draw_page.add(image) + return + + +class LOImpress(LODrawImpress): + + def __init__(self, obj): + super().__init__(obj) + + +class LODraw(LODrawImpress): + + def __init__(self, obj): + super().__init__(obj) + + +class LOMath(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + +class LOBasicIde(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + +class LOCellRange(object): + + def __init__(self, obj, doc): + self._obj = obj + self._doc = doc + self._init_values() + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def __getitem__(self, index): + return LOCellRange(self.obj[index], self.doc) + + def _init_values(self): + self._type_obj = self.obj.ImplementationName + self._type_content = EMPTY + + if self._type_obj == OBJ_CELL: + self._type_content = self.obj.getType() + return + + @property + def obj(self): + return self._obj + + @property + def doc(self): + return self._doc + + @property + def type(self): + return self._type_obj + + @property + def type_content(self): + return self._type_content + + @property + def first(self): + if self.type == OBJ_RANGES: + obj = LOCellRange(self.obj[0][0,0], self.doc) + else: + obj = LOCellRange(self.obj[0,0], self.doc) + return obj + + @property + def value(self): + v = None + if self._type_content == VALUE: + v = self.obj.getValue() + elif self._type_content == TEXT: + v = self.obj.getString() + elif self._type_content == FORMULA: + v = self.obj.getFormula() + return v + @value.setter + def value(self, data): + if isinstance(data, str): + if data.startswith('='): + self.obj.setFormula(data) + else: + self.obj.setString(data) + elif isinstance(data, (int, float)): + self.obj.setValue(data) + + @property + def data(self): + return self.obj.getDataArray() + @data.setter + def data(self, values): + if isinstance(values, list): + values = tuple(values) + self.obj.setDataArray(values) + + def offset(self, col=1, row=0): + a = self.address + col = a.Column + col + row = a.Row + row + return LOCellRange(self.sheet[row,col], self.doc) + + @property + def sheet(self): + return self.obj.Spreadsheet + + @property + def draw_page(self): + return self.sheet.getDrawPage() + + @property + def name(self): + return self.obj.AbsoluteName + + @property + def address(self): + if self._type_obj == OBJ_CELL: + a = self.obj.getCellAddress() + elif self._type_obj == OBJ_RANGE: + a = self.obj.getRangeAddress() + else: + a = self.obj.getRangeAddressesAsString() + return a + + @property + def current_region(self): + cursor = self.sheet.createCursorByRange(self.obj[0,0]) + cursor.collapseToCurrentRegion() + return LOCellRange(self.sheet[cursor.AbsoluteName], self.doc) + + def insert_image(self, path, **kwargs): + s = self.obj.Size + w = kwargs.get('width', s.Width) + h = kwargs.get('Height', s.Height) + img = self.doc.create_instance('com.sun.star.drawing.GraphicObjectShape') + img.GraphicURL = _path_url(path) + self.draw_page.add(img) + img.Anchor = self.obj + img.setSize(Size(w, h)) + return + + +class EventsListenerBase(unohelper.Base, XEventListener): + + def __init__(self, controller, window=None): + self._controller = controller + self._window = window + + def disposing(self, event): + self._controller = None + if not self._window is None: + self._window.setMenuBar(None) + + +class EventsButton(EventsListenerBase, XActionListener): + + def __init__(self, controller): + super().__init__(controller) + + def actionPerformed(self, event): + name = event.Source.Model.Name + event_name = '{}_action'.format(name) + if hasattr(self._controller, event_name): + getattr(self._controller, event_name)(event) + return + + +class EventsMouse(EventsListenerBase, XMouseListener): + + def __init__(self, controller): + super().__init__(controller) + + def mousePressed(self, event): + name = event.Source.Model.Name + event_name = '{}_click'.format(name) + if event.ClickCount == 2: + event_name = '{}_double_click'.format(name) + if hasattr(self._controller, event_name): + getattr(self._controller, event_name)(event) + return + + def mouseReleased(self, event): + pass + + def mouseEntered(self, event): + pass + + def mouseExited(self, event): + pass + + +class UnoBaseObject(object): + + def __init__(self, obj): + self._obj = obj + self._model = self.obj.Model + self._rules = {} + + @property + def obj(self): + return self._obj + + @property + def model(self): + return self._model + + @property + def name(self): + return self.model.Name + + @property + def parent(self): + return self.obj.getContext() + + @property + def x(self): + return self.model.PositionX + @x.setter + def x(self, value): + self.model.PositionX = value + + @property + def y(self): + return self.model.PositionY + @y.setter + def y(self, value): + self.model.PositionY = value + + @property + def width(self): + return self._model.Width + @width.setter + def width(self, value): + self._model.Width = value + + @property + def height(self): + return self._model.Height + @height.setter + def height(self, value): + self._model.Height = value + + @property + def tag(self): + return self.model.Tag + @tag.setter + def tag(self, value): + self.model.Tag = value + + @property + def step(self): + return self.model.Step + @step.setter + def step(self, value): + self.model.Step = value + + @property + def rules(self): + return self._rules + @rules.setter + def rules(self, value): + self._rules = value + + def set_focus(self): + self.obj.setFocus() + return + + def center(self, horizontal=True, vertical=False): + p = self.parent.Model + w = p.Width + h = p.Height + if horizontal: + x = w / 2 - self.width / 2 + self.x = x + if vertical: + y = h / 2 - self.height / 2 + self.y = y + return + + def move(self, origin, x=0, y=5): + w = 0 + h = 0 + if x: + w = origin.width + if y: + h = origin.height + x = origin.x + x + w + y = origin.y + y + h + self.x = x + self.y = y + return + + +class UnoLabel(UnoBaseObject): + + def __init__(self, obj): + super().__init__(obj) + + @property + def value(self): + return self.model.Label + @value.setter + def value(self, value): + self.model.Label = value + + +class UnoButton(UnoBaseObject): + + def __init__(self, obj): + super().__init__(obj) + # ~ self._set_icon() + + def _set_icon(self): + icon_name = self.tag.strip() + if icon_name: + path_icon = _file_url('{}/img/{}'.format(CURRENT_PATH, icon_name)) + self._model.ImageURL = path_icon + if self.value: + self._model.ImageAlign = 0 + return + + @property + def value(self): + return self.model.Label + @value.setter + def value(self, value): + self.model.Label = value + + +class UnoText(UnoBaseObject): + + def __init__(self, obj): + super().__init__(obj) + + @property + def value(self): + return self.model.Text + @value.setter + def value(self, value): + self.model.Text = value + + def validate(self): + + return + + +class UnoListBox(UnoBaseObject): + + def __init__(self, obj): + super().__init__(obj) + self._data = [] + + @property + def value(self): + return self.obj.SelectedItem + + @property + def data(self): + return self._data + @data.setter + def data(self, values): + self._data = list(sorted(values)) + self.model.StringItemList = self.data + return + + +class LODialog(object): + + def __init__(self, properties): + self._obj = self._create(properties) + self._init_values() + + def _init_values(self): + self._model = self._obj.Model + self._init_controls() + self._events = None + # ~ self._response = None + return + + def _create(self, properties): + path = properties.pop('Path', '') + if path: + dp = create_instance('com.sun.star.awt.DialogProvider2', True) + return dp.createDialog(_path_url(path)) + + if 'Library' in properties: + location = properties['Location'] + if location == 'user': + location = 'application' + dp = create_instance('com.sun.star.awt.DialogProvider2', True) + path = 'vnd.sun.star.script:{}.{}?location={}'.format( + properties['Library'], properties['Name'], location) + return dp.createDialog(path) + + dlg = create_instance('com.sun.star.awt.UnoControlDialog', True) + model = create_instance('com.sun.star.awt.UnoControlDialogModel', True) + toolkit = create_instance('com.sun.star.awt.Toolkit', True) + set_properties(model, properties) + dlg.setModel(model) + dlg.setVisible(False) + dlg.createPeer(toolkit, None) + + return dlg + + def _init_controls(self): + + return + + @property + def obj(self): + return self._obj + + @property + def model(self): + return self._model + + @property + def events(self): + return self._events + @events.setter + def events(self, controllers): + self._events = controllers + self._connect_listeners() + + def _connect_listeners(self): + + return + + def _add_listeners(self, control): + if self.events is None: + return + + listeners = { + 'addActionListener': EventsButton, + 'addMouseListener': EventsMouse, + } + for key, value in listeners.items(): + if hasattr(control.obj, key): + getattr(control.obj, key)(listeners[key](self.events)) + return + + def open(self): + return self.obj.execute() + + def close(self, value=0): + return self.obj.endDialog(value) + + def _get_control_model(self, control): + services = { + 'label': 'com.sun.star.awt.UnoControlFixedTextModel', + 'button': 'com.sun.star.awt.UnoControlButtonModel', + 'text': 'com.sun.star.awt.UnoControlEditModel', + 'listbox': 'com.sun.star.awt.UnoControlListBoxModel', + 'link': 'com.sun.star.awt.UnoControlFixedHyperlinkModel', + 'roadmap': 'com.sun.star.awt.UnoControlRoadmapModel', + 'image': 'com.sun.star.awt.UnoControlImageControlModel', + 'groupbox': 'com.sun.star.awt.UnoControlGroupBoxModel', + 'radio': 'com.sun.star.awt.UnoControlRadioButtonModel', + 'tree': 'com.sun.star.awt.tree.TreeControlModel', + 'grid': 'com.sun.star.awt.grid.UnoControlGridModel', + } + return services[control] + + def _get_custom_class(self, tipo, obj): + classes = { + 'label': UnoLabel, + 'button': UnoButton, + 'text': UnoText, + 'listbox': UnoListBox, + # ~ 'link': UnoLink, + # ~ 'tab': UnoTab, + # ~ 'roadmap': UnoRoadmap, + # ~ 'image': UnoImage, + # ~ 'radio': UnoRadio, + # ~ 'groupbox': UnoGroupBox, + # ~ 'tree': UnoTree, + # ~ 'grid': UnoGrid, + } + return classes[tipo](obj) + + def add_control(self, properties): + tipo = properties.pop('Type').lower() + model = self.model.createInstance(self._get_control_model(tipo)) + set_properties(model, properties) + name = properties['Name'] + self.model.insertByName(name, model) + control = self._get_custom_class(tipo, self.obj.getControl(name)) + self._add_listeners(control) + setattr(self, name, control) + return + + +# ~ Python >= 3.7 +# ~ def __getattr__(name): + + +def _get_class_doc(obj): + classes = { + 'calc': LOCalc, + 'writer': LOWriter, + 'base': LOBase, + 'impress': LOImpress, + 'draw': LODraw, + 'math': LOMath, + 'basic': LOBasicIde, + } + type_doc = get_type_doc(obj) + return classes[type_doc](obj) + + +def get_document(): + doc = None + desktop = get_desktop() + try: + doc = _get_class_doc(desktop.getCurrentComponent()) + except Exception as e: + log.error(e) + return doc + + +def get_selection(): + return get_document().selection + + +def get_cell(*args): + if args: + index = args + if len(index) == 1: + index = args[0] + cell = get_document().get_cell(index) + else: + cell = get_selection().first + return cell + + +def active_cell(): + return get_cell() + + +def create_dialog(properties): + return LODialog(properties) + + +def set_properties(model, properties): + if 'X' in properties: + properties['PositionX'] = properties.pop('X') + if 'Y' in properties: + properties['PositionY'] = properties.pop('Y') + keys = tuple(properties.keys()) + values = tuple(properties.values()) + model.setPropertyValues(keys, values) + return diff --git a/files/ZAZBarCode_v0.1.0.oxt b/files/ZAZBarCode_v0.1.0.oxt new file mode 100644 index 0000000..9abfc0b Binary files /dev/null and b/files/ZAZBarCode_v0.1.0.oxt differ diff --git a/images/barcode.png b/images/barcode.png new file mode 100644 index 0000000..c2cfa47 Binary files /dev/null and b/images/barcode.png differ diff --git a/images/barcode_16.bmp b/images/barcode_16.bmp new file mode 100644 index 0000000..10246a3 Binary files /dev/null and b/images/barcode_16.bmp differ diff --git a/images/logo.png b/images/logo.png new file mode 100644 index 0000000..2f210ed Binary files /dev/null and b/images/logo.png differ diff --git a/source/Addons.xcu b/source/Addons.xcu new file mode 100644 index 0000000..49732c5 --- /dev/null +++ b/source/Addons.xcu @@ -0,0 +1,325 @@ + + + + + + + ZAZ BarCode + ZAZ BarCode + + + _self + + + + + Insert BarCode + Insertar Código + + + service:net.elmau.zaz.BarCode?ask + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument,com.sun.star.presentation.PresentationDocument,com.sun.star.drawing.DrawingDocument + + + %origin%/images/barcode + + + + + Insert CODE39 + Insertar CODE39 + + + service:net.elmau.zaz.BarCode?code39 + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert CODE128 + Insertar CODE128 + + + service:net.elmau.zaz.BarCode?code128 + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert EAN + Insertar EAN + + + service:net.elmau.zaz.BarCode?ean + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert EAN8 + Insertar EAN8 + + + service:net.elmau.zaz.BarCode?ean8 + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert EAN13 + Insertar EAN13 + + + service:net.elmau.zaz.BarCode?ean13 + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert GS1 + Insertar GS1 + + + service:net.elmau.zaz.BarCode?gs1 + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert GTIN + Insertar GTIN + + + service:net.elmau.zaz.BarCode?gtin + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert ISBN + Insertar ISBN + + + service:net.elmau.zaz.BarCode?isbn + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert ISBN10 + Insertar ISBN10 + + + service:net.elmau.zaz.BarCode?isbn10 + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert ISBN13 + Insertar ISBN13 + + + service:net.elmau.zaz.BarCode?isbn13 + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert ISSN + Insertar ISSN + + + service:net.elmau.zaz.BarCode?issn + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert JAN + Insertar JAN + + + service:net.elmau.zaz.BarCode?jan + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert PZN + Insertar PZN + + + service:net.elmau.zaz.BarCode?pzn + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert UPC + Insertar UPC + + + service:net.elmau.zaz.BarCode?upc + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert UPCA + Insertar UPCA + + + service:net.elmau.zaz.BarCode?upca + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + Insert QRCODE + Insertar QRCODE + + + service:net.elmau.zaz.BarCode?qrcode + + + _self + + + com.sun.star.sheet.SpreadsheetDocument,com.sun.star.text.TextDocument + + + %origin%/images/barcode + + + + + + + + diff --git a/source/META-INF/manifest.xml b/source/META-INF/manifest.xml new file mode 100644 index 0000000..559e3c0 --- /dev/null +++ b/source/META-INF/manifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/source/ZAZBarCode.py b/source/ZAZBarCode.py new file mode 100644 index 0000000..00d03c8 --- /dev/null +++ b/source/ZAZBarCode.py @@ -0,0 +1,216 @@ +import uno +import unohelper +from com.sun.star.task import XJobExecutor + +import qrcode +import qrcode.image.svg as svg +from barcode import generate + +import easymacro as app + + +ID_EXTENSION = 'net.elmau.zaz.BarCode' +SERVICE = ('com.sun.star.task.Job',) +TITLE = 'ZAZ BarCode' +QR = 'qrcode' + + +class Controllers(object): + + def __init__(self, dlg): + self.d = dlg + + def button_action(self, event): + if not self.d.listbox.value: + self.d.listbox.set_focus() + msg = 'Select barcode type' + app.warning(msg, TITLE) + return + if not self.d.text.value.strip(): + self.d.text.set_focus() + msg = 'Data field is mandatory' + app.warning(msg, TITLE) + return + + self.d.close(1) + return + + +class ZAZBarCode(unohelper.Base, XJobExecutor): + + def __init__(self, ctx): + self.ctx = ctx + self._data = '' + self._type = '' + + def trigger(self, args): + self._type = args + if args == 'ask' and not self._get_values(): + return + + doc = app.get_document() + getattr(self, '_insert_in_{}'.format(doc.type))(doc) + return + + def _create_code(self, tmp_file): + if self._type == QR: + factory = svg.SvgImage + img = qrcode.make(self._data, image_factory=factory) + img.save(tmp_file.name) + else: + try: + generate(self._type, self._data, output=tmp_file) + except Exception as e: + return str(e) + return '' + + def _get_values(self): + self._type = '' + dlg = self._create_dialog() + if dlg.open(): + self._data = dlg.text.value.strip() + self._type = dlg.listbox.value + return True + + return False + + def _insert_in_calc(self, doc): + cell = doc.get_cell() + if not self._data: + self._data = cell.value + if not self._data: + msg = 'Select data' + self._show_error(msg) + return + + tf = app.get_temp_file() + result = self._create_code(tf) + if result: + tf.close() + self._show_error(result) + return + + cell = cell.offset() + cell.insert_image(tf.name) + tf.close() + return + + def _insert_in_writer(self, doc): + doc = app.get_document() + sel = app.get_selection() + if not self._data: + self._data = sel.string + if not self._data: + msg = 'Select data' + self._show_error(msg) + return + + tf = app.get_temp_file() + result = self._create_code(tf) + if result: + tf.close() + self._show_error(result) + return + + doc.insert_image(tf.name) + tf.close() + return + + def _insert_in_draw(self, doc): + tf = app.get_temp_file() + result = self._create_code(tf) + if result: + tf.close() + self._show_error(result) + return + + doc.insert_image(tf.name) + tf.close() + return + + def _insert_in_impress(self, doc): + self._insert_in_draw(doc) + return + + def _show_error(self, error): + msg = 'Error in: {}\n\n{}'.format(self._type, error) + app.error(error) + app.errorbox(msg, TITLE) + return + + def _create_dialog(self): + args = { + 'Name': 'dialog', + 'Title': TITLE, + 'Width': 160, + 'Height': 160, + } + dlg = app.create_dialog(args) + dlg.events = Controllers(dlg) + + args = { + 'Type': 'Label', + 'Name': 'lbl_barcode', + 'Label': 'Select barcode type', + 'Width': 55, + 'Height': 15, + 'X': 10, + 'Y': 10, + 'Align': 2, + 'VerticalAlign': 1, + } + dlg.add_control(args) + + args = { + 'Type': 'Label', + 'Name': 'lbl_data', + 'Label': 'Capture data for barcode', + 'Width': 70, + 'Height': 15, + 'VerticalAlign': 1, + } + dlg.add_control(args) + + args = { + 'Type': 'ListBox', + 'Name': 'listbox', + 'Width': 80, + 'Height': 15, + 'Dropdown': True, + } + dlg.add_control(args) + data = ('code39', 'code128', 'ean', 'ean8', 'ean13', 'gs1', 'gtin', + 'isbn', 'isbn10', 'isbn13', 'issn', 'jan', 'pzn', 'upc', 'upca', + 'qrcode') + dlg.listbox.data = data + + args = { + 'Type': 'Text', + 'Name': 'text', + 'Width': 140, + 'Height': 75, + 'MultiLine': True, + 'VScroll': True, + } + dlg.add_control(args) + + args = { + 'Type': 'Button', + 'Name': 'button', + 'Label': 'Insert Barcode', + 'Width': 60, + 'Height': 15, + } + dlg.add_control(args) + + dlg.listbox.move(dlg.lbl_barcode, 5, 0) + dlg.lbl_data.move(dlg.lbl_barcode) + dlg.text.move(dlg.lbl_data) + dlg.button.move(dlg.text, 0, 10) + dlg.button.center() + + return dlg + + +g_ImplementationHelper = unohelper.ImplementationHelper() +g_ImplementationHelper.addImplementation(ZAZBarCode, ID_EXTENSION, SERVICE) diff --git a/source/description.xml b/source/description.xml new file mode 100644 index 0000000..c3521bd --- /dev/null +++ b/source/description.xml @@ -0,0 +1,26 @@ + + + + + + ZAZ Bar Code + ZAZ Códigos de Barras + + + + + + + + + + El Mau + El Mau + + + + + + + + diff --git a/source/description/desc_en.txt b/source/description/desc_en.txt new file mode 100644 index 0000000..e30738b --- /dev/null +++ b/source/description/desc_en.txt @@ -0,0 +1 @@ +Generate and insert barcode in documents \ No newline at end of file diff --git a/source/description/desc_es.txt b/source/description/desc_es.txt new file mode 100644 index 0000000..3c7b6ce --- /dev/null +++ b/source/description/desc_es.txt @@ -0,0 +1 @@ +Genera e inserta codigos de barras en documentos \ No newline at end of file diff --git a/source/images/barcode_16.bmp b/source/images/barcode_16.bmp new file mode 100644 index 0000000..10246a3 Binary files /dev/null and b/source/images/barcode_16.bmp differ diff --git a/source/images/zazbarcode.png b/source/images/zazbarcode.png new file mode 100644 index 0000000..2f210ed Binary files /dev/null and b/source/images/zazbarcode.png differ diff --git a/source/pythonpath/barcode/DejaVuSansMono.ttf b/source/pythonpath/barcode/DejaVuSansMono.ttf new file mode 100755 index 0000000..6bc854d Binary files /dev/null and b/source/pythonpath/barcode/DejaVuSansMono.ttf differ diff --git a/source/pythonpath/barcode/__init__.py b/source/pythonpath/barcode/__init__.py new file mode 100644 index 0000000..0c2592d --- /dev/null +++ b/source/pythonpath/barcode/__init__.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- + +""" + +pyBarcode +========= + +This package provides a simple way to create standard barcodes. +It needs no external packages to be installed, the barcodes are +created as SVG objects. If Pillow is installed, the barcodes can also be +rendered as images (all formats supported by Pillow). +""" + +from barcode.errors import BarcodeNotFoundError +from barcode.codex import Code39, PZN, Code128, Gs1_128 +from barcode.ean import EAN8, EAN13, EAN14, JAN +from barcode.isxn import ISBN10, ISBN13, ISSN +from barcode.upc import UPCA +from barcode.itf import ITF +from barcode.version import version # noqa: F401 + +try: + _strbase = basestring # lint:ok +except NameError: + _strbase = str + + +__BARCODE_MAP = dict( + ean8=EAN8, + ean13=EAN13, + ean=EAN13, + gtin=EAN14, + ean14=EAN14, + jan=JAN, + upc=UPCA, + upca=UPCA, + isbn=ISBN13, + isbn13=ISBN13, + gs1=ISBN13, + isbn10=ISBN10, + issn=ISSN, + code39=Code39, + pzn=PZN, + code128=Code128, + itf=ITF, + gs1_128=Gs1_128, +) + +PROVIDED_BARCODES = list(__BARCODE_MAP) +PROVIDED_BARCODES.sort() + + +def get(name, code=None, writer=None, options=None): + options = options or {} + try: + barcode = __BARCODE_MAP[name.lower()] + except KeyError: + raise BarcodeNotFoundError('The barcode {0!r} you requested is not ' + 'known.'.format(name)) + if code is not None: + return barcode(code, writer, **options) + else: + return barcode + + +def get_class(name): + return get_barcode(name) + + +def generate(name, code, writer=None, output=None, writer_options=None, + text=None, pil=False): + options = writer_options or {} + barcode = get(name, code, writer, options) + if pil: + return barcode.render(writer_options, text) + if isinstance(output, _strbase): + fullname = barcode.save(output, options, text) + return fullname + else: + barcode.write(output, options, text) + + +get_barcode = get +get_barcode_class = get_class diff --git a/source/pythonpath/barcode/base.py b/source/pythonpath/barcode/base.py new file mode 100644 index 0000000..6a42bf5 --- /dev/null +++ b/source/pythonpath/barcode/base.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +"""barcode.base + +""" + +from barcode.writer import SVGWriter + + +class Barcode(object): + + name = '' + + digits = 0 + + default_writer = SVGWriter + + default_writer_options = { + 'module_width': 0.2, + 'module_height': 15.0, + 'quiet_zone': 6.5, + 'font_size': 10, + 'text_distance': 5.0, + 'background': 'white', + 'foreground': 'black', + 'write_text': True, + 'text': '', + } + + def to_ascii(self): + code = self.build() + for i, line in enumerate(code): + code[i] = line.replace('1', 'X').replace('0', ' ') + return '\n'.join(code) + + def __repr__(self): + return '<{0}({1!r})>'.format(self.__class__.__name__, + self.get_fullcode()) + + def build(self): + raise NotImplementedError + + def get_fullcode(self): + """Returns the full code, encoded in the barcode. + + :returns: Full human readable code. + :rtype: String + """ + raise NotImplementedError + + def save(self, filename, options=None, text=None): + """Renders the barcode and saves it in `filename`. + + :parameters: + filename : String + Filename to save the barcode in (without filename + extension). + options : Dict + The same as in `self.render`. + text : str (unicode on Python 2) + Text to render under the barcode. + + :returns: The full filename with extension. + :rtype: String + """ + if text: + output = self.render(options, text) + else: + output = self.render(options) + + _filename = self.writer.save(filename, output) + return _filename + + def write(self, fp, options=None, text=None): + """Renders the barcode and writes it to the file like object + `fp`. + + :parameters: + fp : File like object + Object to write the raw data in. + options : Dict + The same as in `self.render`. + text : str (unicode on Python 2) + Text to render under the barcode. + """ + output = self.render(options, text) + if hasattr(output, 'tostring'): + output.save(fp, format=self.writer.format) + else: + fp.write(output) + + def render(self, writer_options=None, text=None): + """Renders the barcode using `self.writer`. + + :parameters: + writer_options : Dict + Options for `self.writer`, see writer docs for details. + text : str (unicode on Python 2) + Text to render under the barcode. + + :returns: Output of the writers render method. + """ + options = Barcode.default_writer_options.copy() + options.update(writer_options or {}) + if options['write_text'] or text is not None: + if text is not None: + options['text'] = text + else: + options['text'] = self.get_fullcode() + self.writer.set_options(options) + code = self.build() + raw = self.writer.render(code) + return raw diff --git a/source/pythonpath/barcode/charsets/__init__.py b/source/pythonpath/barcode/charsets/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/source/pythonpath/barcode/charsets/code128.py b/source/pythonpath/barcode/charsets/code128.py new file mode 100644 index 0000000..5132e29 --- /dev/null +++ b/source/pythonpath/barcode/charsets/code128.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +import string + +# Charsets for code 128 + +_common = ( + ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', + '-', '.', '/', +) + tuple(string.digits) + ( + ':', ';', '<', '=', '>', '?', '@', +) + tuple(string.ascii_uppercase) + ( + '[', '\\', ']', '^', '_', +) + +_charset_a = _common + ( + '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', + '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f', '\x10', '\x11', + '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', + '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', '\xf3', '\xf2', 'SHIFT', 'TO_C', + 'TO_B', '\xf4', '\xf1', +) + +_charset_b = _common + ('`',) + tuple(string.ascii_lowercase) + ( + '{', '|', '}', '~', '\x7f', '\xf3', '\xf2', 'SHIFT', 'TO_C', '\xf4', + 'TO_A', '\xf1', +) + +ALL = set(_common + _charset_a + _charset_b) +A = dict(((c, i) for i, c in enumerate(_charset_a))) +B = dict(((c, i) for i, c in enumerate(_charset_b))) +C = {'TO_B': 100, 'TO_A': 101, '\xf1': 102} + +CODES = ( + '11011001100', '11001101100', '11001100110', '10010011000', '10010001100', + '10001001100', '10011001000', '10011000100', '10001100100', '11001001000', + '11001000100', '11000100100', '10110011100', '10011011100', '10011001110', + '10111001100', '10011101100', '10011100110', '11001110010', '11001011100', + '11001001110', '11011100100', '11001110100', '11101101110', '11101001100', + '11100101100', '11100100110', '11101100100', '11100110100', '11100110010', + '11011011000', '11011000110', '11000110110', '10100011000', '10001011000', + '10001000110', '10110001000', '10001101000', '10001100010', '11010001000', + '11000101000', '11000100010', '10110111000', '10110001110', '10001101110', + '10111011000', '10111000110', '10001110110', '11101110110', '11010001110', + '11000101110', '11011101000', '11011100010', '11011101110', '11101011000', + '11101000110', '11100010110', '11101101000', '11101100010', '11100011010', + '11101111010', '11001000010', '11110001010', '10100110000', '10100001100', + '10010110000', '10010000110', '10000101100', '10000100110', '10110010000', + '10110000100', '10011010000', '10011000010', '10000110100', '10000110010', + '11000010010', '11001010000', '11110111010', '11000010100', '10001111010', + '10100111100', '10010111100', '10010011110', '10111100100', '10011110100', + '10011110010', '11110100100', '11110010100', '11110010010', '11011011110', + '11011110110', '11110110110', '10101111000', '10100011110', '10001011110', + '10111101000', '10111100010', '11110101000', '11110100010', '10111011110', + '10111101110', '11101011110', '11110101110', '11010000100', '11010010000', + '11010011100', +) + +STOP = '11000111010' + +START_CODES = {'A': 103, 'B': 104, 'C': 105} +TO = {101: START_CODES['A'], 100: START_CODES['B'], 99: START_CODES['C']} diff --git a/source/pythonpath/barcode/charsets/code39.py b/source/pythonpath/barcode/charsets/code39.py new file mode 100644 index 0000000..4031f65 --- /dev/null +++ b/source/pythonpath/barcode/charsets/code39.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +import string + +# Charsets for code 39 +REF = (tuple(string.digits) + tuple(string.ascii_uppercase) + + ('-', '.', ' ', '$', '/', '+', '%')) +B = '1' +E = '0' +CODES = ( + '101000111011101', '111010001010111', '101110001010111', + '111011100010101', '101000111010111', '111010001110101', + '101110001110101', '101000101110111', '111010001011101', + '101110001011101', '111010100010111', '101110100010111', + '111011101000101', '101011100010111', '111010111000101', + '101110111000101', '101010001110111', '111010100011101', + '101110100011101', '101011100011101', '111010101000111', + '101110101000111', '111011101010001', '101011101000111', + '111010111010001', '101110111010001', '101010111000111', + '111010101110001', '101110101110001', '101011101110001', + '111000101010111', '100011101010111', '111000111010101', + '100010111010111', '111000101110101', '100011101110101', + '100010101110111', '111000101011101', '100011101011101', + '100010001000101', '100010001010001', '100010100010001', + '101000100010001', +) + +EDGE = '100010111011101' +MIDDLE = '0' + +# MAP for assigning every symbol (REF) to (reference number, barcode) +MAP = dict(zip(REF, enumerate(CODES))) diff --git a/source/pythonpath/barcode/charsets/ean.py b/source/pythonpath/barcode/charsets/ean.py new file mode 100644 index 0000000..951028a --- /dev/null +++ b/source/pythonpath/barcode/charsets/ean.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + + +EDGE = '101' +MIDDLE = '01010' +CODES = { + 'A': ('0001101', '0011001', '0010011', '0111101', '0100011', + '0110001', '0101111', '0111011', '0110111', '0001011'), + 'B': ('0100111', '0110011', '0011011', '0100001', '0011101', + '0111001', '0000101', '0010001', '0001001', '0010111'), + 'C': ('1110010', '1100110', '1101100', '1000010', '1011100', + '1001110', '1010000', '1000100', '1001000', '1110100'), +} +LEFT_PATTERN = ('AAAAAA', 'AABABB', 'AABBAB', 'AABBBA', 'ABAABB', + 'ABBAAB', 'ABBBAA', 'ABABAB', 'ABABBA', 'ABBABA') diff --git a/source/pythonpath/barcode/charsets/itf.py b/source/pythonpath/barcode/charsets/itf.py new file mode 100644 index 0000000..988db00 --- /dev/null +++ b/source/pythonpath/barcode/charsets/itf.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +# W = Wide bar +# w = wide space +# N = Narrow bar +# n = narrow space + +START = 'NnNn' +STOP = 'WnN' +CODES = ('NNWWN', 'WNNNW', 'NWNNW', 'WWNNN', 'NNWNW', 'WNWNN', 'NWWNN', 'NNNWW', 'WNNWN', 'NWNWN') diff --git a/source/pythonpath/barcode/charsets/upc.py b/source/pythonpath/barcode/charsets/upc.py new file mode 100644 index 0000000..9b625c7 --- /dev/null +++ b/source/pythonpath/barcode/charsets/upc.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + + +EDGE = '101' +MIDDLE = '01010' +CODES = { + 'L': ('0001101', '0011001', '0010011', '0111101', '0100011', + '0110001', '0101111', '0111011', '0110111', '0001011'), + 'R': ('1110010', '1100110', '1101100', '1000010', '1011100', + '1001110', '1010000', '1000100', '1001000', '1110100') +} diff --git a/source/pythonpath/barcode/codex.py b/source/pythonpath/barcode/codex.py new file mode 100644 index 0000000..c747175 --- /dev/null +++ b/source/pythonpath/barcode/codex.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +from barcode.base import Barcode +from barcode.charsets import code128, code39 +from barcode.errors import * + +"""Module: barcode.codex + +:Provided barcodes: Code 39, Code 128, PZN +""" +__docformat__ = 'restructuredtext en' + + +# Sizes +MIN_SIZE = 0.2 +MIN_QUIET_ZONE = 2.54 + + +def check_code(code, name, allowed): + wrong = [] + for char in code: + if char not in allowed: + wrong.append(char) + if wrong: + raise IllegalCharacterError( + 'The following characters are not valid for ' + '{name}: {wrong}'.format(name=name, wrong=', '.join(wrong)) + ) + + +class Code39(Barcode): + """Initializes a new Code39 instance. + + :parameters: + code : String + Code 39 string without \* and checksum (added automatically if + `add_checksum` is True). + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + add_checksum : Boolean + Add the checksum to code or not (default: True). + """ + + name = 'Code 39' + + def __init__(self, code, writer=None, add_checksum=True): + self.code = code.upper() + if add_checksum: + self.code += self.calculate_checksum() + self.writer = writer or Barcode.default_writer() + check_code(self.code, self.name, code39.REF) + + def __unicode__(self): + return self.code + + __str__ = __unicode__ + + def get_fullcode(self): + return self.code + + def calculate_checksum(self): + check = sum([code39.MAP[x][0] for x in self.code]) % 43 + for k, v in code39.MAP.items(): + if check == v[0]: + return k + + def build(self): + chars = [code39.EDGE] + for char in self.code: + chars.append(code39.MAP[char][1]) + chars.append(code39.EDGE) + return [code39.MIDDLE.join(chars)] + + def render(self, writer_options=None, text=None): + options = dict(module_width=MIN_SIZE, quiet_zone=MIN_QUIET_ZONE) + options.update(writer_options or {}) + return Barcode.render(self, options, text) + + +class PZN7(Code39): + """Initializes new German number for pharmaceutical products. + + :parameters: + pzn : String + Code to render. + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + """ + + name = 'Pharmazentralnummer' + + digits = 6 + + def __init__(self, pzn, writer=None): + pzn = pzn[:self.digits] + if not pzn.isdigit(): + raise IllegalCharacterError('PZN can only contain numbers.') + if len(pzn) != self.digits: + raise NumberOfDigitsError('PZN must have {0} digits, not ' + '{1}.'.format(self.digits, len(pzn))) + self.pzn = pzn + self.pzn = '{0}{1}'.format(pzn, self.calculate_checksum()) + Code39.__init__(self, 'PZN-{0}'.format(self.pzn), writer, + add_checksum=False) + + def get_fullcode(self): + return 'PZN-{0}'.format(self.pzn) + + def calculate_checksum(self): + sum_ = sum([int(x) * int(y) for x, y in enumerate(self.pzn, start=2)]) + checksum = sum_ % 11 + if checksum == 10: + raise BarcodeError('Checksum can not be 10 for PZN.') + else: + return checksum + + +class PZN8(PZN7): + """Will be fully added in v0.9.""" + + digits = 7 + + +class Code128(Barcode): + """Initializes a new Code128 instance. The checksum is added automatically + when building the bars. + + :parameters: + code : String + Code 128 string without checksum (added automatically). + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + """ + + name = 'Code 128' + + def __init__(self, code, writer=None): + self.code = code + self.writer = writer or Barcode.default_writer() + self._charset = 'B' + self._buffer = '' + check_code(self.code, self.name, code128.ALL) + + def __unicode__(self): + return self.code + + __str__ = __unicode__ + + @property + def encoded(self): + return self._build() + + def get_fullcode(self): + return self.code + + def _new_charset(self, which): + if which == 'A': + code = self._convert('TO_A') + elif which == 'B': + code = self._convert('TO_B') + elif which == 'C': + code = self._convert('TO_C') + self._charset = which + return [code] + + def _maybe_switch_charset(self, pos): + char = self.code[pos] + next_ = self.code[pos:pos + 10] + + def look_next(): + digits = 0 + for c in next_: + if c.isdigit(): + digits += 1 + else: + break + return digits > 3 + + codes = [] + if self._charset == 'C' and not char.isdigit(): + if char in code128.B: + codes = self._new_charset('B') + elif char in code128.A: + codes = self._new_charset('A') + if len(self._buffer) == 1: + codes.append(self._convert(self._buffer[0])) + self._buffer = '' + elif self._charset == 'B': + if look_next(): + codes = self._new_charset('C') + elif char not in code128.B: + if char in code128.A: + codes = self._new_charset('A') + elif self._charset == 'A': + if look_next(): + codes = self._new_charset('C') + elif char not in code128.A: + if char in code128.B: + codes = self._new_charset('B') + return codes + + def _convert(self, char): + if self._charset == 'A': + return code128.A[char] + elif self._charset == 'B': + return code128.B[char] + elif self._charset == 'C': + if char in code128.C: + return code128.C[char] + elif char.isdigit(): + self._buffer += char + if len(self._buffer) == 2: + value = int(self._buffer) + self._buffer = '' + return value + + def _try_to_optimize(self, encoded): + if encoded[1] in code128.TO: + encoded[:2] = [code128.TO[encoded[1]]] + return encoded + + def _calculate_checksum(self, encoded): + cs = [encoded[0]] + for i, code_num in enumerate(encoded[1:], start=1): + cs.append(i * code_num) + return sum(cs) % 103 + + def _build(self): + encoded = [code128.START_CODES[self._charset]] + for i, char in enumerate(self.code): + encoded.extend(self._maybe_switch_charset(i)) + code_num = self._convert(char) + if code_num is not None: + encoded.append(code_num) + # Finally look in the buffer + if len(self._buffer) == 1: + encoded.extend(self._new_charset('B')) + encoded.append(self._convert(self._buffer[0])) + self._buffer = '' + encoded = self._try_to_optimize(encoded) + return encoded + + def build(self): + encoded = self._build() + encoded.append(self._calculate_checksum(encoded)) + code = '' + for code_num in encoded: + code += code128.CODES[code_num] + code += code128.STOP + code += '11' + return [code] + + def render(self, writer_options=None, text=None): + options = dict(module_width=MIN_SIZE, quiet_zone=MIN_QUIET_ZONE) + options.update(writer_options or {}) + return Barcode.render(self, options, text) + + +class Gs1_128(Code128): + """ + following the norm, a gs1-128 barcode is a subset of code 128 barcode, + it can be generated by prepending the code with the FNC1 character + https://en.wikipedia.org/wiki/GS1-128 + https://www.gs1-128.info/ + """ + + name = 'GS1-128' + + FNC1_CHAR = '\xf1' + + def __init__(self, code, writer=None): + code = self.FNC1_CHAR + code + super(Gs1_128, self).__init__(code, writer) + + def get_fullcode(self): + return super(Gs1_128, self).get_fullcode()[1:] + + +# For pre 0.8 compatibility +PZN = PZN7 diff --git a/source/pythonpath/barcode/ean.py b/source/pythonpath/barcode/ean.py new file mode 100644 index 0000000..f3a447c --- /dev/null +++ b/source/pythonpath/barcode/ean.py @@ -0,0 +1,199 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +from barcode.base import Barcode +from barcode.charsets import ean as _ean +from barcode.errors import * + +"""Module: barcode.ean + +:Provided barcodes: EAN-14, EAN-13, EAN-8, JAN +""" +__docformat__ = 'restructuredtext en' + +# Python 3 +try: + reduce +except NameError: + from functools import reduce + + +# EAN13 Specs (all sizes in mm) +SIZES = dict(SC0=0.27, SC1=0.297, SC2=0.33, SC3=0.363, SC4=0.396, SC5=0.445, + SC6=0.495, SC7=0.544, SC8=0.61, SC9=0.66) + + +class EuropeanArticleNumber13(Barcode): + """Initializes EAN13 object. + + :parameters: + ean : String + The ean number as string. + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + """ + + name = 'EAN-13' + + digits = 12 + + def __init__(self, ean, writer=None, **kwargs): + no_checksum = False + if "no_checksum" in kwargs.keys(): + no_checksum = kwargs["no_checksum"] + ean = ean[:self.digits] + if not ean.isdigit(): + raise IllegalCharacterError('EAN code can only contain numbers.') + if len(ean) != self.digits: + raise NumberOfDigitsError('EAN must have {0} digits, not ' + '{1}.'.format(self.digits, len(ean))) + self.ean = ean + # If no checksum + if no_checksum: + # Add a thirteen char if given in parameter, + # otherwise pad with zero + self.ean = '{0}{1}'.format( + ean, ean[self.digits] if len(ean) > self.digits else 0 + ) + else: + self.ean = '{0}{1}'.format(ean, self.calculate_checksum()) + self.writer = writer or Barcode.default_writer() + + def __unicode__(self): + return self.ean + + __str__ = __unicode__ + + def get_fullcode(self): + return self.ean + + def calculate_checksum(self): + """Calculates the checksum for EAN13-Code. + + :returns: The checksum for `self.ean`. + :rtype: Integer + """ + def sum_(x, y): return int(x) + int(y) + evensum = reduce(sum_, self.ean[-2::-2]) + oddsum = reduce(sum_, self.ean[-1::-2]) + return (10 - ((evensum + oddsum * 3) % 10)) % 10 + + def build(self): + """Builds the barcode pattern from `self.ean`. + + :returns: The pattern as string + :rtype: String + """ + code = _ean.EDGE[:] + pattern = _ean.LEFT_PATTERN[int(self.ean[0])] + for i, number in enumerate(self.ean[1:7]): + code += _ean.CODES[pattern[i]][int(number)] + code += _ean.MIDDLE + for number in self.ean[7:]: + code += _ean.CODES['C'][int(number)] + code += _ean.EDGE + return [code] + + def to_ascii(self): + """Returns an ascii representation of the barcode. + + :rtype: String + """ + code = self.build() + for i, line in enumerate(code): + code[i] = line.replace('1', '|').replace('0', ' ') + return '\n'.join(code) + + def render(self, writer_options=None, text=None): + options = dict(module_width=SIZES['SC2']) + options.update(writer_options or {}) + return Barcode.render(self, options, text) + + +class JapanArticleNumber(EuropeanArticleNumber13): + """Initializes JAN barcode. + + :parameters: + jan : String + The jan number as string. + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + """ + + name = 'JAN' + + valid_country_codes = list(range(450, 460)) + list(range(490, 500)) + + def __init__(self, jan, writer=None): + if int(jan[:3]) not in JapanArticleNumber.valid_country_codes: + raise WrongCountryCodeError("Country code isn't between 450-460 " + "or 490-500.") + EuropeanArticleNumber13.__init__(self, jan, writer) + + +class EuropeanArticleNumber8(EuropeanArticleNumber13): + """Represents an EAN-8 barcode. See EAN13's __init__ for details. + + :parameters: + ean : String + The ean number as string. + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + """ + + name = 'EAN-8' + + digits = 7 + + def __init__(self, ean, writer=None): + EuropeanArticleNumber13.__init__(self, ean, writer) + + def build(self): + """Builds the barcode pattern from `self.ean`. + + :returns: The pattern as string + :rtype: String + """ + code = _ean.EDGE[:] + for number in self.ean[:4]: + code += _ean.CODES['A'][int(number)] + code += _ean.MIDDLE + for number in self.ean[4:]: + code += _ean.CODES['C'][int(number)] + code += _ean.EDGE + return [code] + + +class EuropeanArticleNumber14(EuropeanArticleNumber13): + """Represents an EAN-14 barcode. See EAN13's __init__ for details. + + :parameters: + ean : String + The ean number as string. + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + """ + + name = 'EAN-14' + digits = 13 + + def calculate_checksum(self): + """Calculates the checksum for EAN13-Code. + + :returns: The checksum for `self.ean`. + :rtype: Integer + """ + + def sum_(x, y): return int(x) + int(y) + + evensum = reduce(sum_, self.ean[::2]) + oddsum = reduce(sum_, self.ean[1::2]) + return (10 - (((evensum * 3) + oddsum) % 10)) % 10 + + +# Shortcuts +EAN14 = EuropeanArticleNumber14 +EAN13 = EuropeanArticleNumber13 +EAN8 = EuropeanArticleNumber8 +JAN = JapanArticleNumber diff --git a/source/pythonpath/barcode/errors.py b/source/pythonpath/barcode/errors.py new file mode 100644 index 0000000..20f9459 --- /dev/null +++ b/source/pythonpath/barcode/errors.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +"""barcode.errors +""" +__docformat__ = 'restructuredtext en' + + +class BarcodeError(Exception): + def __init__(self, msg): + self.msg = msg + + def __str__(self): + return self.msg + + +class IllegalCharacterError(BarcodeError): + """Raised when a barcode-string contains illegal characters.""" + + +class BarcodeNotFoundError(BarcodeError): + """Raised when an unknown barcode is requested.""" + + +class NumberOfDigitsError(BarcodeError): + """Raised when the number of digits do not match.""" + + +class WrongCountryCodeError(BarcodeError): + """Raised when a JAN (Japan Article Number) don't starts with 450-459 + or 490-499. + """ diff --git a/source/pythonpath/barcode/isxn.py b/source/pythonpath/barcode/isxn.py new file mode 100644 index 0000000..c5911ff --- /dev/null +++ b/source/pythonpath/barcode/isxn.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +from barcode.ean import EuropeanArticleNumber13 +from barcode.errors import * + +"""Module: barcode.isxn + +:Provided barcodes: ISBN-13, ISBN-10, ISSN + +This module provides some special codes, which are no standalone barcodes. +All codes where transformed to EAN-13 barcodes. In every case, the checksum +is new calculated. + +Example:: + + >>> from barcode import get_barcode + >>> ISBN = get_barcode('isbn10') + >>> isbn = ISBN('0132354187') + >>> unicode(isbn) + '0132354187' + >>> isbn.get_fullcode() + '9780132354189' + >>> # Test with wrong checksum + >>> isbn = ISBN('0132354180') + >>> unicode(isbn) + '0132354187' + +""" +__docformat__ = 'restructuredtext en' + + +class InternationalStandardBookNumber13(EuropeanArticleNumber13): + """Initializes new ISBN-13 barcode. + + :parameters: + isbn : String + The isbn number as string. + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + """ + + name = 'ISBN-13' + + def __init__(self, isbn, writer=None): + isbn = isbn.replace('-', '') + self.isbn13 = isbn + if isbn[:3] not in ('978', '979'): + raise WrongCountryCodeError('ISBN must start with 978 or 979.') + if isbn[:3] == '979': + if isbn[3:5] not in ('10', '11'): + raise BarcodeError('ISBN must start with 97910 or 97911.') + EuropeanArticleNumber13.__init__(self, isbn, writer) + + +class InternationalStandardBookNumber10(InternationalStandardBookNumber13): + """Initializes new ISBN-10 barcode. This code is rendered as EAN-13 by + prefixing it with 978. + + :parameters: + isbn : String + The isbn number as string. + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + """ + + name = 'ISBN-10' + + digits = 9 + + def __init__(self, isbn, writer=None): + isbn = isbn.replace('-', '') + isbn = isbn[:self.digits] + self.isbn10 = isbn + self.isbn10 = '{0}{1}'.format(isbn, self._calculate_checksum()) + InternationalStandardBookNumber13.__init__(self, '978' + isbn, writer) + + def _calculate_checksum(self): + tmp = sum([x * int(y) for x, y in enumerate(self.isbn10[:9], + start=1)]) % 11 + if tmp == 10: + return 'X' + else: + return tmp + + def __unicode__(self): + return self.isbn10 + + __str__ = __unicode__ + + +class InternationalStandardSerialNumber(EuropeanArticleNumber13): + """Initializes new ISSN barcode. This code is rendered as EAN-13 + by prefixing it with 977 and adding 00 between code and checksum. + + :parameters: + issn : String + The issn number as string. + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + """ + + name = 'ISSN' + + digits = 7 + + def __init__(self, issn, writer=None): + issn = issn.replace('-', '') + issn = issn[:self.digits] + self.issn = issn + self.issn = '{0}{1}'.format(issn, self._calculate_checksum()) + EuropeanArticleNumber13.__init__(self, self.make_ean(), writer) + + def _calculate_checksum(self): + tmp = 11 - sum([x * int(y) for x, y in + enumerate(reversed(self.issn[:7]), start=2)]) % 11 + if tmp == 10: + return 'X' + else: + return tmp + + def make_ean(self): + return '977{0}00{1}'.format(self.issn[:7], self._calculate_checksum()) + + def __unicode__(self): + return self.issn + + __str__ = __unicode__ + + +# Shortcuts +ISBN13 = InternationalStandardBookNumber13 +ISBN10 = InternationalStandardBookNumber10 +ISSN = InternationalStandardSerialNumber diff --git a/source/pythonpath/barcode/itf.py b/source/pythonpath/barcode/itf.py new file mode 100644 index 0000000..c307255 --- /dev/null +++ b/source/pythonpath/barcode/itf.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +from barcode.base import Barcode +from barcode.charsets import itf +from barcode.errors import * + +"""Module: barcode.itf + +:Provided barcodes: Interleaved 2 of 5 +""" +__docformat__ = 'restructuredtext en' + + +MIN_SIZE = 0.2 +MIN_QUIET_ZONE = 6.4 + + +class ITF(Barcode): + """Initializes a new ITF instance. + + :parameters: + code : String + ITF (Interleaved 2 of 5) numeric string + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + narrow: Integer + Width of the narrow elements (default: 2) + wide: Integer + Width of the wide elements (default: 5) + wide/narrow must be in the range 2..3 + """ + + name = 'ITF' + + def __init__(self, code, writer=None, narrow=2, wide=5): + if not code.isdigit(): + raise IllegalCharacterError('ITF code can only contain numbers.') + # Length must be even, prepend 0 if necessary + if len(code) % 2 != 0: + code = '0' + code + self.code = code + self.writer = writer or Barcode.default_writer() + self.narrow = narrow + self.wide = wide + + def __unicode__(self): + return self.code + + __str__ = __unicode__ + + def get_fullcode(self): + return self.code + + def build(self): + data = itf.START + for i in range(0, len(self.code), 2): + bars_digit = int(self.code[i]) + spaces_digit = int(self.code[i+1]) + for j in range(5): + data += itf.CODES[bars_digit][j].upper() + data += itf.CODES[spaces_digit][j].lower() + data += itf.STOP + raw = '' + for e in data: + if e == 'W': + raw += '1' * self.wide + if e == 'w': + raw += '0' * self.wide + if e == 'N': + raw += '1' * self.narrow + if e == 'n': + raw += '0' * self.narrow + return [raw] + + def render(self, writer_options, text=None): + options = dict(module_width=MIN_SIZE/self.narrow, + quiet_zone=MIN_QUIET_ZONE) + options.update(writer_options or {}) + return Barcode.render(self, options, text) diff --git a/source/pythonpath/barcode/pybarcode.py b/source/pythonpath/barcode/pybarcode.py new file mode 100644 index 0000000..c1938fa --- /dev/null +++ b/source/pythonpath/barcode/pybarcode.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- + +from __future__ import print_function + +import os + +import barcode + +from argparse import ArgumentParser + +from barcode.writer import ImageWriter, SVGWriter +from barcode.version import version + +# Optional PyQt4 GUI +try: + from PyQt4 import QtCore +except ImportError: + QtCore = None # lint:ok + +# No GUI available yet +QtCore = None +IMG_FORMATS = ('BMP', 'GIF', 'JPEG', 'MSP', 'PCX', 'PNG', 'TIFF', 'XBM') + + +def open_gui(args, parser=None): + pass + + +def list_types(args, parser=None): + print('\npyBarcode available barcode formats:') + print(', '.join(barcode.PROVIDED_BARCODES)) + print('\n') + print('Available image formats') + print('Standard: svg') + if ImageWriter is not None: + print('Pillow:', ', '.join(IMG_FORMATS)) + else: + print('Pillow: disabled') + print('\n') + + +def create_barcode(args, parser): + args.type = args.type.upper() + if args.type != 'SVG' and args.type not in IMG_FORMATS: + parser.error( + 'Unknown type {type}. Try list action for available ' + 'types.'.format(type=args.type) + ) + args.barcode = args.barcode.lower() + if args.barcode not in barcode.PROVIDED_BARCODES: + parser.error( + 'Unknown barcode {bc}. Try list action for available ' + 'barcodes.'.format(bc=args.barcode) + ) + if args.type != 'SVG': + opts = dict(format=args.type) + writer = ImageWriter() + else: + opts = dict(compress=args.compress) + writer = SVGWriter() + out = os.path.normpath(os.path.abspath(args.output)) + name = barcode.generate(args.barcode, args.code, writer, out, opts, + args.text) + print('New barcode saved as {0}.'.format(name)) + + +def main(): + msg = [] + if ImageWriter is None: + msg.append( + 'Image output disabled (Pillow not found), --type option disabled.' + ) + else: + msg.append( + 'Image output enabled, use --type option to give image ' + 'format (png, jpeg, ...).' + ) + if QtCore is None: + msg.append('PyQt not found, gui action disabled.') + else: + msg.append('PyQt found. Use gui action to get a simple GUI.') + parser = ArgumentParser( + description='Create standard barcodes via cli.', epilog=' '.join(msg) + ) + parser.add_argument('-v', '--version', action='version', + version='%(prog)s ' + version) + subparsers = parser.add_subparsers(title='Actions') + create_parser = subparsers.add_parser('create', help='Create a barcode ' + 'with the given options.') + create_parser.add_argument('code', help='Code to render as barcode.') + create_parser.add_argument('output', help='Filename for output ' + 'without extension, e. g. mybarcode.') + create_parser.add_argument( + '-c', '--compress', action='store_true', + help='Compress output, only recognized if type is svg.' + ) + create_parser.add_argument('-b', '--barcode', help='Barcode to use ' + '[default: %(default)s].') + create_parser.add_argument('--text', help='Text to show under the ' + 'barcode.') + if ImageWriter is not None: + create_parser.add_argument('-t', '--type', help='Type of output ' + '[default: %(default)s].') + list_parser = subparsers.add_parser('list', help='List available ' + 'image and code types.') + list_parser.set_defaults(func=list_types) + if QtCore is not None: + gui_parser = subparsers.add_parser('gui', help='Opens a simple ' + 'PyQt GUI to create barcodes.') + gui_parser.set_defaults(func=open_gui) + create_parser.set_defaults(type='svg', compress=False, func=create_barcode, + barcode='code39', text=None) + args = parser.parse_args() + try: + func = args.func + except AttributeError: + parser.error("You need to tell me what to do.") + else: + func(args, parser) + + +if __name__ == '__main__': + main() diff --git a/source/pythonpath/barcode/upc.py b/source/pythonpath/barcode/upc.py new file mode 100644 index 0000000..cd68259 --- /dev/null +++ b/source/pythonpath/barcode/upc.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +from barcode.base import Barcode +from barcode.charsets import upc as _upc +from barcode.errors import * + +try: + reduce +except NameError: + from functools import reduce + +"""Module: barcode.upc + +:Provided barcodes: UPC-A +""" +__docformat__ = 'restructuredtext en' + + +class UniversalProductCodeA(Barcode): + """Initializes new UPC-A barcode. + + :parameters: + upc : String + The upc number as string. + writer : barcode.writer Instance + The writer to render the barcode (default: SVGWriter). + make_ean: boolean + """ + + name = 'UPC-A' + + digits = 11 + + def __init__(self, upc, writer=None, make_ean=False): + self.ean = make_ean + upc = upc[:self.digits] + if not upc.isdigit(): + raise IllegalCharacterError('UPC code can only contain numbers.') + if len(upc) != self.digits: + raise NumberOfDigitsError('UPC must have {0} digits, not ' + '{1}.'.format(self.digits, len(upc))) + self.upc = upc + self.upc = '{}{}'.format(upc, self.calculate_checksum()) + self.writer = writer or Barcode.default_writer() + + def __unicode__(self): + if self.ean: + return '0' + self.upc + else: + return self.upc + + __str__ = __unicode__ + + def get_fullcode(self): + if self.ean: + return '0' + self.upc + else: + return self.upc + + def calculate_checksum(self): + """Calculates the checksum for UPCA/UPC codes + + :return: The checksum for 'self.upc' + :rtype: Integer + """ + def sum_(x, y): return int(x) + int(y) + upc = self.upc[0:self.digits] + oddsum = reduce(sum_, upc[::2]) + evensum = reduce(sum_, upc[1::2]) + check = (evensum + oddsum * 3) % 10 + if check == 0: + return 0 + else: + return 10 - check + + def build(self): + """Builds the barcode pattern from 'self.upc' + + :return: The pattern as string + :rtype: String + """ + code = _upc.EDGE[:] + + for i, number in enumerate(self.upc[0:6]): + code += _upc.CODES['L'][int(number)] + + code += _upc.MIDDLE + + for number in self.upc[6:]: + code += _upc.CODES['R'][int(number)] + + code += _upc.EDGE + + return [code] + + def to_ascii(self): + """Returns an ascii representation of the barcode. + + :rtype: String + """ + + code = self.build() + for i, line in enumerate(code): + code[i] = line.replace('1', '|').replace('0', '_') + return '\n'.join(code) + + def render(self, writer_options=None, text=None): + options = dict(module_width=0.33) + options.update(writer_options or {}) + return Barcode.render(self, options, text) + +UPCA = UniversalProductCodeA diff --git a/source/pythonpath/barcode/version.py b/source/pythonpath/barcode/version.py new file mode 100644 index 0000000..f9f5476 --- /dev/null +++ b/source/pythonpath/barcode/version.py @@ -0,0 +1,4 @@ +# coding: utf-8 +# file generated by setuptools_scm +# don't change, don't track in version control +version = '0.10.0' diff --git a/source/pythonpath/barcode/writer.py b/source/pythonpath/barcode/writer.py new file mode 100644 index 0000000..415f26f --- /dev/null +++ b/source/pythonpath/barcode/writer.py @@ -0,0 +1,337 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +import gzip +import os +import xml.dom + +from barcode.version import version + +try: + import Image + import ImageDraw + import ImageFont +except ImportError: + try: + from PIL import Image, ImageDraw, ImageFont # lint:ok + except ImportError: + import logging + log = logging.getLogger('pyBarcode') + log.info('Pillow not found. Image output disabled') + Image = ImageDraw = ImageFont = None # lint:ok + + +def mm2px(mm, dpi=300): + return (mm * dpi) / 25.4 + + +def pt2mm(pt): + return pt * 0.352777778 + + +def _set_attributes(element, **attributes): + for key, value in attributes.items(): + element.setAttribute(key, value) + + +def create_svg_object(): + imp = xml.dom.getDOMImplementation() + doctype = imp.createDocumentType( + 'svg', + '-//W3C//DTD SVG 1.1//EN', + 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd' + ) + document = imp.createDocument(None, 'svg', doctype) + _set_attributes(document.documentElement, version='1.1', + xmlns='http://www.w3.org/2000/svg') + return document + + +SIZE = '{0:.3f}mm' +COMMENT = 'Autogenerated with python-barcode {0}'.format(version) +PATH = os.path.dirname(os.path.abspath(__file__)) +FONT = os.path.join(PATH, 'DejaVuSansMono.ttf') + + +class BaseWriter(object): + """Baseclass for all writers. + + Initializes the basic writer options. Childclasses can add more + attributes and can set them directly or using + `self.set_options(option=value)`. + + :parameters: + initialize : Function + Callback for initializing the inheriting writer. + Is called: `callback_initialize(raw_code)` + paint_module : Function + Callback for painting one barcode module. + Is called: `callback_paint_module(xpos, ypos, width, color)` + paint_text : Function + Callback for painting the text under the barcode. + Is called: `callback_paint_text(xpos, ypos)` using `self.text` + as text. + finish : Function + Callback for doing something with the completely rendered + output. + Is called: `return callback_finish()` and must return the + rendered output. + """ + + def __init__(self, initialize=None, paint_module=None, paint_text=None, + finish=None): + self._callbacks = dict( + initialize=initialize, paint_module=paint_module, + paint_text=paint_text, finish=finish + ) + self.module_width = 10 + self.module_height = 10 + self.font_size = 10 + self.quiet_zone = 6.5 + self.background = 'white' + self.foreground = 'black' + self.text = '' + self.human = '' # human readable text + self.text_distance = 5 + self.center_text = True + + def calculate_size(self, modules_per_line, number_of_lines, dpi=300): + """Calculates the size of the barcode in pixel. + + :parameters: + modules_per_line : Integer + Number of modules in one line. + number_of_lines : Integer + Number of lines of the barcode. + dpi : Integer + DPI to calculate. + + :returns: Width and height of the barcode in pixel. + :rtype: Tuple + """ + width = 2 * self.quiet_zone + modules_per_line * self.module_width + height = 2.0 + self.module_height * number_of_lines + if self.font_size and self.text: + height += pt2mm(self.font_size) / 2 + self.text_distance + return int(mm2px(width, dpi)), int(mm2px(height, dpi)) + + def save(self, filename, output): + """Saves the rendered output to `filename`. + + :parameters: + filename : String + Filename without extension. + output : String + The rendered output. + + :returns: The full filename with extension. + :rtype: String + """ + raise NotImplementedError + + def register_callback(self, action, callback): + """Register one of the three callbacks if not given at instance + creation. + + :parameters: + action : String + One of 'initialize', 'paint_module', 'paint_text', 'finish'. + callback : Function + The callback function for the given action. + """ + self._callbacks[action] = callback + + def set_options(self, options): + """Sets the given options as instance attributes (only + if they are known). + + :parameters: + options : Dict + All known instance attributes and more if the childclass + has defined them before this call. + + :rtype: None + """ + for key, val in options.items(): + key = key.lstrip('_') + if hasattr(self, key): + setattr(self, key, val) + + def render(self, code): + """Renders the barcode to whatever the inheriting writer provides, + using the registered callbacks. + + :parameters: + code : List + List of strings matching the writer spec + (only contain 0 or 1). + """ + if self._callbacks['initialize'] is not None: + self._callbacks['initialize'](code) + ypos = 1.0 + for cc, line in enumerate(code): + """ + Pack line to list give better gfx result, otherwise in can + result in aliasing gaps + '11010111' -> [2, -1, 1, -1, 3] + """ + line += ' ' + c = 1 + mlist = [] + for i in range(0, len(line) - 1): + if line[i] == line[i+1]: + c += 1 + else: + if line[i] == "1": + mlist.append(c) + else: + mlist.append(-c) + c = 1 + # Left quiet zone is x startposition + xpos = self.quiet_zone + bxs = xpos # x start of barcode + for mod in mlist: + if mod < 1: + color = self.background + else: + color = self.foreground + # remove painting for background colored tiles? + self._callbacks['paint_module']( + xpos, ypos, self.module_width * abs(mod), color + ) + xpos += self.module_width * abs(mod) + bxe = xpos + # Add right quiet zone to every line, except last line, + # quiet zone already provided with background, + # should it be removed complety? + if (cc + 1) != len(code): + self._callbacks['paint_module']( + xpos, ypos, self.quiet_zone, self.background + ) + ypos += self.module_height + if self.text and self._callbacks['paint_text'] is not None: + ypos += self.text_distance + if self.center_text: + # better center position for text + xpos = bxs + ((bxe - bxs) / 2.0) + else: + xpos = bxs + self._callbacks['paint_text'](xpos, ypos) + return self._callbacks['finish']() + + +class SVGWriter(BaseWriter): + + def __init__(self): + BaseWriter.__init__(self, self._init, self._create_module, + self._create_text, self._finish) + self.compress = False + self.dpi = 25.4 + self._document = None + self._root = None + self._group = None + + def _init(self, code): + width, height = self.calculate_size(len(code[0]), len(code), self.dpi) + self._document = create_svg_object() + self._root = self._document.documentElement + attributes = dict(width=SIZE.format(width), height=SIZE.format(height)) + _set_attributes(self._root, **attributes) + self._root.appendChild(self._document.createComment(COMMENT)) + # create group for easier handling in 3rd party software + # like corel draw, inkscape, ... + group = self._document.createElement('g') + attributes = dict(id='barcode_group') + _set_attributes(group, **attributes) + self._group = self._root.appendChild(group) + background = self._document.createElement('rect') + attributes = dict(width='100%', height='100%', + style='fill:{0}'.format(self.background)) + _set_attributes(background, **attributes) + self._group.appendChild(background) + + def _create_module(self, xpos, ypos, width, color): + element = self._document.createElement('rect') + attributes = dict(x=SIZE.format(xpos), y=SIZE.format(ypos), + width=SIZE.format(width), + height=SIZE.format(self.module_height), + style='fill:{0};'.format(color)) + _set_attributes(element, **attributes) + self._group.appendChild(element) + + def _create_text(self, xpos, ypos): + element = self._document.createElement('text') + attributes = dict(x=SIZE.format(xpos), y=SIZE.format(ypos), + style='fill:{0};font-size:{1}pt;text-anchor:' + 'middle;'.format(self.foreground, + self.font_size)) + _set_attributes(element, **attributes) + # check option to override self.text with self.human (barcode as + # human readable data, can be used to print own formats) + if self.human != '': + barcodetext = self.human + else: + barcodetext = self.text + text_element = self._document.createTextNode(barcodetext) + element.appendChild(text_element) + self._group.appendChild(element) + + def _finish(self): + if self.compress: + return self._document.toxml(encoding='UTF-8') + else: + return self._document.toprettyxml(indent=4 * ' ', newl=os.linesep, + encoding='UTF-8') + + def save(self, filename, output): + if self.compress: + _filename = '{0}.svgz'.format(filename) + f = gzip.open(_filename, 'wb') + f.write(output) + f.close() + else: + _filename = '{0}.svg'.format(filename) + with open(_filename, 'wb') as f: + f.write(output) + return _filename + + +if Image is None: + ImageWriter = None +else: + class ImageWriter(BaseWriter): + + def __init__(self): + BaseWriter.__init__(self, self._init, self._paint_module, + self._paint_text, self._finish) + self.format = 'PNG' + self.dpi = 300 + self._image = None + self._draw = None + + def _init(self, code): + size = self.calculate_size(len(code[0]), len(code), self.dpi) + self._image = Image.new('RGB', size, self.background) + self._draw = ImageDraw.Draw(self._image) + + def _paint_module(self, xpos, ypos, width, color): + size = [(mm2px(xpos, self.dpi), mm2px(ypos, self.dpi)), + (mm2px(xpos + width, self.dpi), + mm2px(ypos + self.module_height, self.dpi))] + self._draw.rectangle(size, outline=color, fill=color) + + def _paint_text(self, xpos, ypos): + font = ImageFont.truetype(FONT, self.font_size * 2) + width, height = font.getsize(self.text) + pos = (mm2px(xpos, self.dpi) - width // 2, + mm2px(ypos, self.dpi) - height // 4) + self._draw.text(pos, self.text, font=font, fill=self.foreground) + + def _finish(self): + return self._image + + def save(self, filename, output): + filename = '{0}.{1}'.format(filename, self.format.lower()) + output.save(filename, self.format.upper()) + return filename diff --git a/source/pythonpath/easymacro.py b/source/pythonpath/easymacro.py new file mode 100644 index 0000000..76de6cf --- /dev/null +++ b/source/pythonpath/easymacro.py @@ -0,0 +1,1000 @@ +#!/usr/bin/env python3 + +# == Rapid Develop Macros in LibreOffice == + +# ~ This file is part of ZAZ. + +# ~ ZAZ is free software: you can 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. + +# ~ ZAZ is distributed in the hope that it will be useful, +# ~ but WITHOUT ANY WARRANTY; without even the implied warranty of +# ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# ~ GNU General Public License for more details. + +# ~ You should have received a copy of the GNU General Public License +# ~ along with ZAZ. If not, see . + + +import getpass +import logging +import os +import platform +import sys +import tempfile +import threading +import time +from functools import wraps + +import uno +import unohelper +from com.sun.star.beans import PropertyValue +from com.sun.star.awt import MessageBoxButtons as MSG_BUTTONS +from com.sun.star.awt.MessageBoxResults import YES +from com.sun.star.awt.PosSize import POSSIZE, SIZE +from com.sun.star.awt import Size, Point +from com.sun.star.table.CellContentType import EMPTY, VALUE, TEXT, FORMULA + +from com.sun.star.text.TextContentAnchorType import AS_CHARACTER + +from com.sun.star.lang import XEventListener +from com.sun.star.awt import XActionListener +from com.sun.star.awt import XMouseListener + + +FILE_NAME_DEBUG = 'debug.log' +MSG_LANG = { + 'es': { + 'OK': 'Aceptar', + 'Cancel': 'Cancelar', + } +} + +FORMAT = '%(asctime)s - %(levelname)s - %(message)s' +DATE = '%d/%m/%Y %H:%M:%S' +LEVEL_ERROR = logging.getLevelName(logging.ERROR) +LEVEL_DEBUG = logging.getLevelName(logging.DEBUG) +LEVEL_INFO = logging.getLevelName(logging.INFO) +logging.addLevelName(logging.ERROR, f'\033[1;41m{LEVEL_ERROR}\033[1;0m') +logging.addLevelName(logging.DEBUG, f'\x1b[33m{LEVEL_DEBUG}\033[1;0m') +logging.addLevelName(logging.INFO, f'\x1b[32m{LEVEL_INFO}\033[1;0m') +logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt=DATE) +log = logging.getLogger(__name__) + + +OBJ_CELL = 'ScCellObj' +OBJ_RANGE = 'ScCellRangeObj' +OBJ_RANGES = 'ScCellRangesObj' +OBJ_TYPE_RANGES = (OBJ_CELL, OBJ_RANGE, OBJ_RANGES) + +CTX = uno.getComponentContext() +SM = CTX.getServiceManager() + + +def create_instance(name, with_context=False): + if with_context: + instance = SM.createInstanceWithContext(name, CTX) + else: + instance = SM.createInstance(name) + return instance + + +def _get_config(key, node_name): + name = 'com.sun.star.configuration.ConfigurationProvider' + service = 'com.sun.star.configuration.ConfigurationAccess' + cp = create_instance(name, True) + node = PropertyValue(Name='nodepath', Value=node_name) + try: + ca = cp.createInstanceWithArguments(service, (node,)) + if ca and (ca.hasByName(key)): + data = ca.getPropertyValue(key) + return data + except Exception as e: + log.error(e) + return '' + + +OS = sys.platform +USER = getpass.getuser() +PC = platform.node() + +LANGUAGE = _get_config('ooLocale', 'org.openoffice.Setup/L10N/') +NAME = TITLE = _get_config('ooName', 'org.openoffice.Setup/Product') +VERSION = _get_config('ooSetupVersion', 'org.openoffice.Setup/Product') +# ~ DESKTOP = create_instance('com.sun.star.frame.Desktop', True) + +INFO_DEBUG = '{}\n\n{}\n\n{}'.format( + sys.version, platform.platform(), '\n'.join(sys.path)) + + +def mri(obj): + m = create_instance('mytools.Mri') + if m is None: + msg = 'Extension MRI not found' + error(msg) + return + + m.inspect(obj) + return + + +def debug(info): + log.debug(info) + return + + +def error(info): + log.error(info) + return + + +def catch_exception(f): + @wraps(f) + def func(*args, **kwargs): + try: + return f(*args, **kwargs) + except Exception as e: + log.error(f.__name__, exc_info=True) + return func + + +def run_in_thread(fn): + def run(*k, **kw): + t = threading.Thread(target=fn, args=k, kwargs=kw) + t.start() + return t + return run + + +def _(msg): + L = LANGUAGE.split('-')[0] + if L == 'en': + return msg + + if not L in MSG_LANG: + return msg + + return MSG_LANG[L][msg] + + +def msgbox(message, title=TITLE, buttons=MSG_BUTTONS.BUTTONS_OK, type_msg='infobox'): + """ Create message box + type_msg: infobox, warningbox, errorbox, querybox, messbox + http://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1awt_1_1XMessageBoxFactory.html + """ + toolkit = create_instance('com.sun.star.awt.Toolkit') + parent = toolkit.getDesktopWindow() + mb = toolkit.createMessageBox(parent, type_msg, buttons, title, str(message)) + return mb.execute() + + +def question(message, title=TITLE): + res = msgbox(message, title, MSG_BUTTONS.BUTTONS_YES_NO, 'querybox') + return res == YES + + +def warning(message, title=TITLE): + return msgbox(message, title, type_msg='warningbox') + + +def errorbox(message, title=TITLE): + return msgbox(message, title, type_msg='errorbox') + + +def get_desktop(): + return create_instance('com.sun.star.frame.Desktop', True) + + +def get_temp_file(): + return tempfile.NamedTemporaryFile() + + +def _path_url(path): + if path.startswith('file://'): + return path + return uno.systemPathToFileUrl(path) + + +def _path_system(path): + if path.startswith('file://'): + return os.path.abspath(uno.fileUrlToSystemPath(path)) + return path + + +def get_type_doc(obj): + services = { + 'calc': 'com.sun.star.sheet.SpreadsheetDocument', + 'writer': 'com.sun.star.text.TextDocument', + 'impress': 'com.sun.star.presentation.PresentationDocument', + 'draw': 'com.sun.star.drawing.DrawingDocument', + 'base': 'com.sun.star.sdb.OfficeDatabaseDocument', + 'math': 'com.sun.star.formula.FormulaProperties', + 'basic': 'com.sun.star.script.BasicIDE', + } + for k, v in services.items(): + if obj.supportsService(v): + return k + return '' + + +# ~ Custom classes + + +class LODocument(object): + + def __init__(self, obj): + self._obj = obj + self._init_values() + + def _init_values(self): + self._type_doc = get_type_doc(self.obj) + self._cc = self.obj.getCurrentController() + return + + @property + def obj(self): + return self._obj + + @property + def type(self): + return self._type_doc + + @property + def title(self): + return self.obj.getTitle() + + @property + def is_saved(self): + return self.obj.hasLocation() + + @property + def is_modified(self): + return self.obj.isModified() + + @property + def is_read_only(self): + return self.obj.isReadOnly() + + @property + def path(self): + return _path_system(self.obj.getURL()) + + @property + def visible(self): + w = self._cc.getFrame().getContainerWindow() + return w.Visible + @visible.setter + def visible(self, value): + w = self._cc.getFrame().getContainerWindow() + w.setVisible(value) + + @property + def zoom(self): + return self._cc.ZoomValue + @zoom.setter + def zoom(self, value): + self._cc.ZoomValue = value + + def create_instance(self, name): + obj = self.obj.createInstance(name) + return obj + + +class LOCalc(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + @property + def obj(self): + return self._obj + + @property + def active(self): + return LOCalcSheet(self._cc.getActiveSheet(), self) + + @property + def selection(self): + sel = self.obj.getCurrentSelection() + if sel.ImplementationName in OBJ_TYPE_RANGES: + sel = LOCellRange(sel, self) + return sel + + def get_cell(self, index=None): + """ + index is str 'A1' + index is tuple (row, col) + """ + if index is None: + cell = self.selection.first + else: + cell = LOCellRange(self.active[index].obj, self) + return cell + + # ~ def create_instance(self, name): + # ~ obj = self.obj.createInstance(name) + # ~ return obj + + +class LOCalcSheet(object): + + def __init__(self, obj, doc): + self._obj = obj + self._doc = doc + self._init_values() + + def __getitem__(self, index): + return LOCellRange(self.obj[index], self.doc) + + def _init_values(self): + return + + @property + def obj(self): + return self._obj + + @property + def doc(self): + return self._doc + + +class LOWriter(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + @property + def obj(self): + return self._obj + + @property + def string(self): + return self._obj.getText().String + + @property + def text(self): + return self._obj.getText() + + @property + def cursor(self): + return self.text.createTextCursor() + + @property + def selection(self): + sel = self._cc.getSelection() + return LOTextRange(sel[0]) + + def insert_content(self, cursor, data, replace=False): + self.text.insertTextContent(cursor, data, replace) + return + + # ~ tt = doc.createInstance('com.sun.star.text.TextTable') + # ~ tt.initialize(5, 2) + + # ~ f = doc.createInstance('com.sun.star.text.TextFrame') + # ~ f.setSize(Size(10000, 500)) + + def insert_image(self, path, **kwargs): + cursor = kwargs.get('cursor', self.selection.cursor.getEnd()) + w = kwargs.get('width', 1000) + h = kwargs.get('Height', 1000) + image = self.create_instance('com.sun.star.text.GraphicObject') + image.GraphicURL = _path_url(path) + image.AnchorType = AS_CHARACTER + image.Width = w + image.Height = h + self.insert_content(cursor, image) + return + + +class LOTextRange(object): + + def __init__(self, obj): + self._obj = obj + + @property + def obj(self): + return self._obj + + @property + def string(self): + return self.obj.String + + @property + def text(self): + return self.obj.getText() + + @property + def cursor(self): + return self.text.createTextCursorByRange(self.obj) + + +class LOBase(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + +class LODrawImpress(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + @property + def draw_page(self): + return self._cc.getCurrentPage() + + @catch_exception + def insert_image(self, path, **kwargs): + w = kwargs.get('width', 3000) + h = kwargs.get('Height', 1000) + x = kwargs.get('X', 1000) + y = kwargs.get('Y', 1000) + + image = self.create_instance('com.sun.star.drawing.GraphicObjectShape') + image.GraphicURL = _path_url(path) + image.Size = Size(w, h) + image.Position = Point(x, y) + self.draw_page.add(image) + return + + +class LOImpress(LODrawImpress): + + def __init__(self, obj): + super().__init__(obj) + + +class LODraw(LODrawImpress): + + def __init__(self, obj): + super().__init__(obj) + + +class LOMath(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + +class LOBasicIde(LODocument): + + def __init__(self, obj): + super().__init__(obj) + + +class LOCellRange(object): + + def __init__(self, obj, doc): + self._obj = obj + self._doc = doc + self._init_values() + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def __getitem__(self, index): + return LOCellRange(self.obj[index], self.doc) + + def _init_values(self): + self._type_obj = self.obj.ImplementationName + self._type_content = EMPTY + + if self._type_obj == OBJ_CELL: + self._type_content = self.obj.getType() + return + + @property + def obj(self): + return self._obj + + @property + def doc(self): + return self._doc + + @property + def type(self): + return self._type_obj + + @property + def type_content(self): + return self._type_content + + @property + def first(self): + if self.type == OBJ_RANGES: + obj = LOCellRange(self.obj[0][0,0], self.doc) + else: + obj = LOCellRange(self.obj[0,0], self.doc) + return obj + + @property + def value(self): + v = None + if self._type_content == VALUE: + v = self.obj.getValue() + elif self._type_content == TEXT: + v = self.obj.getString() + elif self._type_content == FORMULA: + v = self.obj.getFormula() + return v + @value.setter + def value(self, data): + if isinstance(data, str): + if data.startswith('='): + self.obj.setFormula(data) + else: + self.obj.setString(data) + elif isinstance(data, (int, float)): + self.obj.setValue(data) + + @property + def data(self): + return self.obj.getDataArray() + @data.setter + def data(self, values): + if isinstance(values, list): + values = tuple(values) + self.obj.setDataArray(values) + + def offset(self, col=1, row=0): + a = self.address + col = a.Column + col + row = a.Row + row + return LOCellRange(self.sheet[row,col], self.doc) + + @property + def sheet(self): + return self.obj.Spreadsheet + + @property + def draw_page(self): + return self.sheet.getDrawPage() + + @property + def name(self): + return self.obj.AbsoluteName + + @property + def address(self): + if self._type_obj == OBJ_CELL: + a = self.obj.getCellAddress() + elif self._type_obj == OBJ_RANGE: + a = self.obj.getRangeAddress() + else: + a = self.obj.getRangeAddressesAsString() + return a + + @property + def current_region(self): + cursor = self.sheet.createCursorByRange(self.obj[0,0]) + cursor.collapseToCurrentRegion() + return LOCellRange(self.sheet[cursor.AbsoluteName], self.doc) + + def insert_image(self, path, **kwargs): + s = self.obj.Size + w = kwargs.get('width', s.Width) + h = kwargs.get('Height', s.Height) + img = self.doc.create_instance('com.sun.star.drawing.GraphicObjectShape') + img.GraphicURL = _path_url(path) + self.draw_page.add(img) + img.Anchor = self.obj + img.setSize(Size(w, h)) + return + + +class EventsListenerBase(unohelper.Base, XEventListener): + + def __init__(self, controller, window=None): + self._controller = controller + self._window = window + + def disposing(self, event): + self._controller = None + if not self._window is None: + self._window.setMenuBar(None) + + +class EventsButton(EventsListenerBase, XActionListener): + + def __init__(self, controller): + super().__init__(controller) + + def actionPerformed(self, event): + name = event.Source.Model.Name + event_name = '{}_action'.format(name) + if hasattr(self._controller, event_name): + getattr(self._controller, event_name)(event) + return + + +class EventsMouse(EventsListenerBase, XMouseListener): + + def __init__(self, controller): + super().__init__(controller) + + def mousePressed(self, event): + name = event.Source.Model.Name + event_name = '{}_click'.format(name) + if event.ClickCount == 2: + event_name = '{}_double_click'.format(name) + if hasattr(self._controller, event_name): + getattr(self._controller, event_name)(event) + return + + def mouseReleased(self, event): + pass + + def mouseEntered(self, event): + pass + + def mouseExited(self, event): + pass + + +class UnoBaseObject(object): + + def __init__(self, obj): + self._obj = obj + self._model = self.obj.Model + self._rules = {} + + @property + def obj(self): + return self._obj + + @property + def model(self): + return self._model + + @property + def name(self): + return self.model.Name + + @property + def parent(self): + return self.obj.getContext() + + @property + def x(self): + return self.model.PositionX + @x.setter + def x(self, value): + self.model.PositionX = value + + @property + def y(self): + return self.model.PositionY + @y.setter + def y(self, value): + self.model.PositionY = value + + @property + def width(self): + return self._model.Width + @width.setter + def width(self, value): + self._model.Width = value + + @property + def height(self): + return self._model.Height + @height.setter + def height(self, value): + self._model.Height = value + + @property + def tag(self): + return self.model.Tag + @tag.setter + def tag(self, value): + self.model.Tag = value + + @property + def step(self): + return self.model.Step + @step.setter + def step(self, value): + self.model.Step = value + + @property + def rules(self): + return self._rules + @rules.setter + def rules(self, value): + self._rules = value + + def set_focus(self): + self.obj.setFocus() + return + + def center(self, horizontal=True, vertical=False): + p = self.parent.Model + w = p.Width + h = p.Height + if horizontal: + x = w / 2 - self.width / 2 + self.x = x + if vertical: + y = h / 2 - self.height / 2 + self.y = y + return + + def move(self, origin, x=0, y=5): + w = 0 + h = 0 + if x: + w = origin.width + if y: + h = origin.height + x = origin.x + x + w + y = origin.y + y + h + self.x = x + self.y = y + return + + +class UnoLabel(UnoBaseObject): + + def __init__(self, obj): + super().__init__(obj) + + @property + def value(self): + return self.model.Label + @value.setter + def value(self, value): + self.model.Label = value + + +class UnoButton(UnoBaseObject): + + def __init__(self, obj): + super().__init__(obj) + # ~ self._set_icon() + + def _set_icon(self): + icon_name = self.tag.strip() + if icon_name: + path_icon = _file_url('{}/img/{}'.format(CURRENT_PATH, icon_name)) + self._model.ImageURL = path_icon + if self.value: + self._model.ImageAlign = 0 + return + + @property + def value(self): + return self.model.Label + @value.setter + def value(self, value): + self.model.Label = value + + +class UnoText(UnoBaseObject): + + def __init__(self, obj): + super().__init__(obj) + + @property + def value(self): + return self.model.Text + @value.setter + def value(self, value): + self.model.Text = value + + def validate(self): + + return + + +class UnoListBox(UnoBaseObject): + + def __init__(self, obj): + super().__init__(obj) + self._data = [] + + @property + def value(self): + return self.obj.SelectedItem + + @property + def data(self): + return self._data + @data.setter + def data(self, values): + self._data = list(sorted(values)) + self.model.StringItemList = self.data + return + + +class LODialog(object): + + def __init__(self, properties): + self._obj = self._create(properties) + self._init_values() + + def _init_values(self): + self._model = self._obj.Model + self._init_controls() + self._events = None + # ~ self._response = None + return + + def _create(self, properties): + path = properties.pop('Path', '') + if path: + dp = create_instance('com.sun.star.awt.DialogProvider2', True) + return dp.createDialog(_path_url(path)) + + if 'Library' in properties: + location = properties['Location'] + if location == 'user': + location = 'application' + dp = create_instance('com.sun.star.awt.DialogProvider2', True) + path = 'vnd.sun.star.script:{}.{}?location={}'.format( + properties['Library'], properties['Name'], location) + return dp.createDialog(path) + + dlg = create_instance('com.sun.star.awt.UnoControlDialog', True) + model = create_instance('com.sun.star.awt.UnoControlDialogModel', True) + toolkit = create_instance('com.sun.star.awt.Toolkit', True) + set_properties(model, properties) + dlg.setModel(model) + dlg.setVisible(False) + dlg.createPeer(toolkit, None) + + return dlg + + def _init_controls(self): + + return + + @property + def obj(self): + return self._obj + + @property + def model(self): + return self._model + + @property + def events(self): + return self._events + @events.setter + def events(self, controllers): + self._events = controllers + self._connect_listeners() + + def _connect_listeners(self): + + return + + def _add_listeners(self, control): + if self.events is None: + return + + listeners = { + 'addActionListener': EventsButton, + 'addMouseListener': EventsMouse, + } + for key, value in listeners.items(): + if hasattr(control.obj, key): + getattr(control.obj, key)(listeners[key](self.events)) + return + + def open(self): + return self.obj.execute() + + def close(self, value=0): + return self.obj.endDialog(value) + + def _get_control_model(self, control): + services = { + 'label': 'com.sun.star.awt.UnoControlFixedTextModel', + 'button': 'com.sun.star.awt.UnoControlButtonModel', + 'text': 'com.sun.star.awt.UnoControlEditModel', + 'listbox': 'com.sun.star.awt.UnoControlListBoxModel', + 'link': 'com.sun.star.awt.UnoControlFixedHyperlinkModel', + 'roadmap': 'com.sun.star.awt.UnoControlRoadmapModel', + 'image': 'com.sun.star.awt.UnoControlImageControlModel', + 'groupbox': 'com.sun.star.awt.UnoControlGroupBoxModel', + 'radio': 'com.sun.star.awt.UnoControlRadioButtonModel', + 'tree': 'com.sun.star.awt.tree.TreeControlModel', + 'grid': 'com.sun.star.awt.grid.UnoControlGridModel', + } + return services[control] + + def _get_custom_class(self, tipo, obj): + classes = { + 'label': UnoLabel, + 'button': UnoButton, + 'text': UnoText, + 'listbox': UnoListBox, + # ~ 'link': UnoLink, + # ~ 'tab': UnoTab, + # ~ 'roadmap': UnoRoadmap, + # ~ 'image': UnoImage, + # ~ 'radio': UnoRadio, + # ~ 'groupbox': UnoGroupBox, + # ~ 'tree': UnoTree, + # ~ 'grid': UnoGrid, + } + return classes[tipo](obj) + + def add_control(self, properties): + tipo = properties.pop('Type').lower() + model = self.model.createInstance(self._get_control_model(tipo)) + set_properties(model, properties) + name = properties['Name'] + self.model.insertByName(name, model) + control = self._get_custom_class(tipo, self.obj.getControl(name)) + self._add_listeners(control) + setattr(self, name, control) + return + + +# ~ Python >= 3.7 +# ~ def __getattr__(name): + + +def _get_class_doc(obj): + classes = { + 'calc': LOCalc, + 'writer': LOWriter, + 'base': LOBase, + 'impress': LOImpress, + 'draw': LODraw, + 'math': LOMath, + 'basic': LOBasicIde, + } + type_doc = get_type_doc(obj) + return classes[type_doc](obj) + + +def get_document(): + doc = None + desktop = get_desktop() + try: + doc = _get_class_doc(desktop.getCurrentComponent()) + except Exception as e: + log.error(e) + return doc + + +def get_selection(): + return get_document().selection + + +def get_cell(*args): + if args: + index = args + if len(index) == 1: + index = args[0] + cell = get_document().get_cell(index) + else: + cell = get_selection().first + return cell + + +def active_cell(): + return get_cell() + + +def create_dialog(properties): + return LODialog(properties) + + +def set_properties(model, properties): + if 'X' in properties: + properties['PositionX'] = properties.pop('X') + if 'Y' in properties: + properties['PositionY'] = properties.pop('Y') + keys = tuple(properties.keys()) + values = tuple(properties.values()) + model.setPropertyValues(keys, values) + return diff --git a/source/pythonpath/qrcode/LUT.py b/source/pythonpath/qrcode/LUT.py new file mode 100644 index 0000000..99042c5 --- /dev/null +++ b/source/pythonpath/qrcode/LUT.py @@ -0,0 +1,50 @@ +# Store all kinds of lookup table. + + +# # generate rsPoly lookup table. + +# from qrcode import base + +# def create_bytes(rs_blocks): +# for r in range(len(rs_blocks)): +# dcCount = rs_blocks[r].data_count +# ecCount = rs_blocks[r].total_count - dcCount +# rsPoly = base.Polynomial([1], 0) +# for i in range(ecCount): +# rsPoly = rsPoly * base.Polynomial([1, base.gexp(i)], 0) +# return ecCount, rsPoly + +# rsPoly_LUT = {} +# for version in range(1,41): +# for error_correction in range(4): +# rs_blocks_list = base.rs_blocks(version, error_correction) +# ecCount, rsPoly = create_bytes(rs_blocks_list) +# rsPoly_LUT[ecCount]=rsPoly.num +# print(rsPoly_LUT) + +# Result. Usage: input: ecCount, output: Polynomial.num +# e.g. rsPoly = base.Polynomial(LUT.rsPoly_LUT[ecCount], 0) +rsPoly_LUT = { + 7: [1, 127, 122, 154, 164, 11, 68, 117], + 10: [1, 216, 194, 159, 111, 199, 94, 95, 113, 157, 193], + 13: [1, 137, 73, 227, 17, 177, 17, 52, 13, 46, 43, 83, 132, 120], + 15: [1, 29, 196, 111, 163, 112, 74, 10, 105, 105, 139, 132, 151, + 32, 134, 26], + 16: [1, 59, 13, 104, 189, 68, 209, 30, 8, 163, 65, 41, 229, 98, 50, 36, 59], + 17: [1, 119, 66, 83, 120, 119, 22, 197, 83, 249, 41, 143, 134, 85, 53, 125, + 99, 79], + 18: [1, 239, 251, 183, 113, 149, 175, 199, 215, 240, 220, 73, 82, 173, 75, + 32, 67, 217, 146], + 20: [1, 152, 185, 240, 5, 111, 99, 6, 220, 112, 150, 69, 36, 187, 22, 228, + 198, 121, 121, 165, 174], + 22: [1, 89, 179, 131, 176, 182, 244, 19, 189, 69, 40, 28, 137, 29, 123, 67, + 253, 86, 218, 230, 26, 145, 245], + 24: [1, 122, 118, 169, 70, 178, 237, 216, 102, 115, 150, 229, 73, 130, 72, + 61, 43, 206, 1, 237, 247, 127, 217, 144, 117], + 26: [1, 246, 51, 183, 4, 136, 98, 199, 152, 77, 56, 206, 24, 145, 40, 209, + 117, 233, 42, 135, 68, 70, 144, 146, 77, 43, 94], + 28: [1, 252, 9, 28, 13, 18, 251, 208, 150, 103, 174, 100, 41, 167, 12, 247, + 56, 117, 119, 233, 127, 181, 100, 121, 147, 176, 74, 58, 197], + 30: [1, 212, 246, 77, 73, 195, 192, 75, 98, 5, 70, 103, 177, 22, 217, 138, + 51, 181, 246, 72, 25, 18, 46, 228, 74, 216, 195, 11, 106, 130, 150] + } diff --git a/source/pythonpath/qrcode/__init__.py b/source/pythonpath/qrcode/__init__.py new file mode 100644 index 0000000..f6aa53f --- /dev/null +++ b/source/pythonpath/qrcode/__init__.py @@ -0,0 +1,25 @@ +from qrcode.main import QRCode +from qrcode.main import make # noqa +from qrcode.constants import ( # noqa + ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H) + +from qrcode import image # noqa + + +def run_example(data="http://www.lincolnloop.com", *args, **kwargs): + """ + Build an example QR Code and display it. + + There's an even easier way than the code here though: just use the ``make`` + shortcut. + """ + qr = QRCode(*args, **kwargs) + qr.add_data(data) + + im = qr.make_image() + im.show() + + +if __name__ == '__main__': # pragma: no cover + import sys + run_example(*sys.argv[1:]) diff --git a/source/pythonpath/qrcode/base.py b/source/pythonpath/qrcode/base.py new file mode 100644 index 0000000..e84e0f3 --- /dev/null +++ b/source/pythonpath/qrcode/base.py @@ -0,0 +1,356 @@ +from qrcode import constants + +EXP_TABLE = list(range(256)) + +LOG_TABLE = list(range(256)) + +for i in range(8): + EXP_TABLE[i] = 1 << i + +for i in range(8, 256): + EXP_TABLE[i] = ( + EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ + EXP_TABLE[i - 8]) + +for i in range(255): + LOG_TABLE[EXP_TABLE[i]] = i + +RS_BLOCK_OFFSET = { + constants.ERROR_CORRECT_L: 0, + constants.ERROR_CORRECT_M: 1, + constants.ERROR_CORRECT_Q: 2, + constants.ERROR_CORRECT_H: 3, +} + +RS_BLOCK_TABLE = [ + + # L + # M + # Q + # H + + # 1 + [1, 26, 19], + [1, 26, 16], + [1, 26, 13], + [1, 26, 9], + + # 2 + [1, 44, 34], + [1, 44, 28], + [1, 44, 22], + [1, 44, 16], + + # 3 + [1, 70, 55], + [1, 70, 44], + [2, 35, 17], + [2, 35, 13], + + # 4 + [1, 100, 80], + [2, 50, 32], + [2, 50, 24], + [4, 25, 9], + + # 5 + [1, 134, 108], + [2, 67, 43], + [2, 33, 15, 2, 34, 16], + [2, 33, 11, 2, 34, 12], + + # 6 + [2, 86, 68], + [4, 43, 27], + [4, 43, 19], + [4, 43, 15], + + # 7 + [2, 98, 78], + [4, 49, 31], + [2, 32, 14, 4, 33, 15], + [4, 39, 13, 1, 40, 14], + + # 8 + [2, 121, 97], + [2, 60, 38, 2, 61, 39], + [4, 40, 18, 2, 41, 19], + [4, 40, 14, 2, 41, 15], + + # 9 + [2, 146, 116], + [3, 58, 36, 2, 59, 37], + [4, 36, 16, 4, 37, 17], + [4, 36, 12, 4, 37, 13], + + # 10 + [2, 86, 68, 2, 87, 69], + [4, 69, 43, 1, 70, 44], + [6, 43, 19, 2, 44, 20], + [6, 43, 15, 2, 44, 16], + + # 11 + [4, 101, 81], + [1, 80, 50, 4, 81, 51], + [4, 50, 22, 4, 51, 23], + [3, 36, 12, 8, 37, 13], + + # 12 + [2, 116, 92, 2, 117, 93], + [6, 58, 36, 2, 59, 37], + [4, 46, 20, 6, 47, 21], + [7, 42, 14, 4, 43, 15], + + # 13 + [4, 133, 107], + [8, 59, 37, 1, 60, 38], + [8, 44, 20, 4, 45, 21], + [12, 33, 11, 4, 34, 12], + + # 14 + [3, 145, 115, 1, 146, 116], + [4, 64, 40, 5, 65, 41], + [11, 36, 16, 5, 37, 17], + [11, 36, 12, 5, 37, 13], + + # 15 + [5, 109, 87, 1, 110, 88], + [5, 65, 41, 5, 66, 42], + [5, 54, 24, 7, 55, 25], + [11, 36, 12, 7, 37, 13], + + # 16 + [5, 122, 98, 1, 123, 99], + [7, 73, 45, 3, 74, 46], + [15, 43, 19, 2, 44, 20], + [3, 45, 15, 13, 46, 16], + + # 17 + [1, 135, 107, 5, 136, 108], + [10, 74, 46, 1, 75, 47], + [1, 50, 22, 15, 51, 23], + [2, 42, 14, 17, 43, 15], + + # 18 + [5, 150, 120, 1, 151, 121], + [9, 69, 43, 4, 70, 44], + [17, 50, 22, 1, 51, 23], + [2, 42, 14, 19, 43, 15], + + # 19 + [3, 141, 113, 4, 142, 114], + [3, 70, 44, 11, 71, 45], + [17, 47, 21, 4, 48, 22], + [9, 39, 13, 16, 40, 14], + + # 20 + [3, 135, 107, 5, 136, 108], + [3, 67, 41, 13, 68, 42], + [15, 54, 24, 5, 55, 25], + [15, 43, 15, 10, 44, 16], + + # 21 + [4, 144, 116, 4, 145, 117], + [17, 68, 42], + [17, 50, 22, 6, 51, 23], + [19, 46, 16, 6, 47, 17], + + # 22 + [2, 139, 111, 7, 140, 112], + [17, 74, 46], + [7, 54, 24, 16, 55, 25], + [34, 37, 13], + + # 23 + [4, 151, 121, 5, 152, 122], + [4, 75, 47, 14, 76, 48], + [11, 54, 24, 14, 55, 25], + [16, 45, 15, 14, 46, 16], + + # 24 + [6, 147, 117, 4, 148, 118], + [6, 73, 45, 14, 74, 46], + [11, 54, 24, 16, 55, 25], + [30, 46, 16, 2, 47, 17], + + # 25 + [8, 132, 106, 4, 133, 107], + [8, 75, 47, 13, 76, 48], + [7, 54, 24, 22, 55, 25], + [22, 45, 15, 13, 46, 16], + + # 26 + [10, 142, 114, 2, 143, 115], + [19, 74, 46, 4, 75, 47], + [28, 50, 22, 6, 51, 23], + [33, 46, 16, 4, 47, 17], + + # 27 + [8, 152, 122, 4, 153, 123], + [22, 73, 45, 3, 74, 46], + [8, 53, 23, 26, 54, 24], + [12, 45, 15, 28, 46, 16], + + # 28 + [3, 147, 117, 10, 148, 118], + [3, 73, 45, 23, 74, 46], + [4, 54, 24, 31, 55, 25], + [11, 45, 15, 31, 46, 16], + + # 29 + [7, 146, 116, 7, 147, 117], + [21, 73, 45, 7, 74, 46], + [1, 53, 23, 37, 54, 24], + [19, 45, 15, 26, 46, 16], + + # 30 + [5, 145, 115, 10, 146, 116], + [19, 75, 47, 10, 76, 48], + [15, 54, 24, 25, 55, 25], + [23, 45, 15, 25, 46, 16], + + # 31 + [13, 145, 115, 3, 146, 116], + [2, 74, 46, 29, 75, 47], + [42, 54, 24, 1, 55, 25], + [23, 45, 15, 28, 46, 16], + + # 32 + [17, 145, 115], + [10, 74, 46, 23, 75, 47], + [10, 54, 24, 35, 55, 25], + [19, 45, 15, 35, 46, 16], + + # 33 + [17, 145, 115, 1, 146, 116], + [14, 74, 46, 21, 75, 47], + [29, 54, 24, 19, 55, 25], + [11, 45, 15, 46, 46, 16], + + # 34 + [13, 145, 115, 6, 146, 116], + [14, 74, 46, 23, 75, 47], + [44, 54, 24, 7, 55, 25], + [59, 46, 16, 1, 47, 17], + + # 35 + [12, 151, 121, 7, 152, 122], + [12, 75, 47, 26, 76, 48], + [39, 54, 24, 14, 55, 25], + [22, 45, 15, 41, 46, 16], + + # 36 + [6, 151, 121, 14, 152, 122], + [6, 75, 47, 34, 76, 48], + [46, 54, 24, 10, 55, 25], + [2, 45, 15, 64, 46, 16], + + # 37 + [17, 152, 122, 4, 153, 123], + [29, 74, 46, 14, 75, 47], + [49, 54, 24, 10, 55, 25], + [24, 45, 15, 46, 46, 16], + + # 38 + [4, 152, 122, 18, 153, 123], + [13, 74, 46, 32, 75, 47], + [48, 54, 24, 14, 55, 25], + [42, 45, 15, 32, 46, 16], + + # 39 + [20, 147, 117, 4, 148, 118], + [40, 75, 47, 7, 76, 48], + [43, 54, 24, 22, 55, 25], + [10, 45, 15, 67, 46, 16], + + # 40 + [19, 148, 118, 6, 149, 119], + [18, 75, 47, 31, 76, 48], + [34, 54, 24, 34, 55, 25], + [20, 45, 15, 61, 46, 16] + +] + + +def glog(n): + if n < 1: # pragma: no cover + raise ValueError("glog(%s)" % n) + return LOG_TABLE[n] + + +def gexp(n): + return EXP_TABLE[n % 255] + + +class Polynomial(object): + + def __init__(self, num, shift): + if not num: # pragma: no cover + raise Exception("%s/%s" % (len(num), shift)) + + for offset in range(len(num)): + if num[offset] != 0: + break + else: + offset += 1 + + self.num = num[offset:] + [0] * shift + + def __getitem__(self, index): + return self.num[index] + + def __iter__(self): + return iter(self.num) + + def __len__(self): + return len(self.num) + + def __mul__(self, other): + num = [0] * (len(self) + len(other) - 1) + + for i, item in enumerate(self): + for j, other_item in enumerate(other): + num[i + j] ^= gexp(glog(item) + glog(other_item)) + + return Polynomial(num, 0) + + def __mod__(self, other): + difference = len(self) - len(other) + if difference < 0: + return self + + ratio = glog(self[0]) - glog(other[0]) + + num = [ + item ^ gexp(glog(other_item) + ratio) + for item, other_item in zip(self, other)] + if difference: + num.extend(self[-difference:]) + + # recursive call + return Polynomial(num, 0) % other + + +class RSBlock(object): + + def __init__(self, total_count, data_count): + self.total_count = total_count + self.data_count = data_count + + +def rs_blocks(version, error_correction): + if error_correction not in RS_BLOCK_OFFSET: # pragma: no cover + raise Exception( + "bad rs block @ version: %s / error_correction: %s" % + (version, error_correction)) + offset = RS_BLOCK_OFFSET[error_correction] + rs_block = RS_BLOCK_TABLE[(version - 1) * 4 + offset] + + blocks = [] + + for i in range(0, len(rs_block), 3): + count, total_count, data_count = rs_block[i:i + 3] + for j in range(count): + blocks.append(RSBlock(total_count, data_count)) + + return blocks diff --git a/source/pythonpath/qrcode/console_scripts.py b/source/pythonpath/qrcode/console_scripts.py new file mode 100755 index 0000000..cb62beb --- /dev/null +++ b/source/pythonpath/qrcode/console_scripts.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +""" +qr - Convert stdin (or the first argument) to a QR Code. + +When stdout is a tty the QR Code is printed to the terminal and when stdout is +a pipe to a file an image is written. The default image format is PNG. +""" +import sys +import optparse +import os +import qrcode +# The next block is added to get the terminal to display properly on MS platforms +if sys.platform.startswith(('win', 'cygwin')): # pragma: no cover + import colorama + colorama.init() + +default_factories = { + 'pil': 'qrcode.image.pil.PilImage', + 'pymaging': 'qrcode.image.pure.PymagingImage', + 'svg': 'qrcode.image.svg.SvgImage', + 'svg-fragment': 'qrcode.image.svg.SvgFragmentImage', + 'svg-path': 'qrcode.image.svg.SvgPathImage', +} + +error_correction = { + 'L': qrcode.ERROR_CORRECT_L, + 'M': qrcode.ERROR_CORRECT_M, + 'Q': qrcode.ERROR_CORRECT_Q, + 'H': qrcode.ERROR_CORRECT_H, +} + + +def main(args=None): + if args is None: + args = sys.argv[1:] + from pkg_resources import get_distribution + version = get_distribution('qrcode').version + parser = optparse.OptionParser(usage=__doc__.strip(), version=version) + parser.add_option( + "--factory", help="Full python path to the image factory class to " + "create the image with. You can use the following shortcuts to the " + "built-in image factory classes: {0}.".format( + ", ".join(sorted(default_factories.keys())))) + parser.add_option( + "--optimize", type=int, help="Optimize the data by looking for chunks " + "of at least this many characters that could use a more efficient " + "encoding method. Use 0 to turn off chunk optimization.") + parser.add_option( + "--error-correction", type='choice', + choices=sorted(error_correction.keys()), default='M', + help="The error correction level to use. Choices are L (7%), " + "M (15%, default), Q (25%), and H (30%).") + opts, args = parser.parse_args(args) + + qr = qrcode.QRCode( + error_correction=error_correction[opts.error_correction]) + + if opts.factory: + module = default_factories.get(opts.factory, opts.factory) + if '.' not in module: + parser.error("The image factory is not a full python path") + module, name = module.rsplit('.', 1) + imp = __import__(module, {}, [], [name]) + image_factory = getattr(imp, name) + else: + image_factory = None + + if args: + data = args[0] + else: + # Use sys.stdin.buffer if available (Python 3) avoiding + # UnicodeDecodeErrors. + stdin_buffer = getattr(sys.stdin, 'buffer', sys.stdin) + data = stdin_buffer.read() + if opts.optimize is None: + qr.add_data(data) + else: + qr.add_data(data, optimize=opts.optimize) + + if image_factory is None and os.isatty(sys.stdout.fileno()): + qr.print_ascii(tty=True) + return + + img = qr.make_image(image_factory=image_factory) + + sys.stdout.flush() + # Use sys.stdout.buffer if available (Python 3), avoiding + # UnicodeDecodeErrors. + stdout_buffer = getattr(sys.stdout, 'buffer', None) + if not stdout_buffer: + if sys.platform == 'win32': # pragma: no cover + import msvcrt + msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) + stdout_buffer = sys.stdout + + img.save(stdout_buffer) + + +if __name__ == "__main__": + main() diff --git a/source/pythonpath/qrcode/constants.py b/source/pythonpath/qrcode/constants.py new file mode 100644 index 0000000..385dda0 --- /dev/null +++ b/source/pythonpath/qrcode/constants.py @@ -0,0 +1,5 @@ +# QR error correct levels +ERROR_CORRECT_L = 1 +ERROR_CORRECT_M = 0 +ERROR_CORRECT_Q = 3 +ERROR_CORRECT_H = 2 diff --git a/source/pythonpath/qrcode/exceptions.py b/source/pythonpath/qrcode/exceptions.py new file mode 100644 index 0000000..b37bd30 --- /dev/null +++ b/source/pythonpath/qrcode/exceptions.py @@ -0,0 +1,2 @@ +class DataOverflowError(Exception): + pass diff --git a/source/pythonpath/qrcode/image/__init__.py b/source/pythonpath/qrcode/image/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/source/pythonpath/qrcode/image/base.py b/source/pythonpath/qrcode/image/base.py new file mode 100644 index 0000000..d7b24f7 --- /dev/null +++ b/source/pythonpath/qrcode/image/base.py @@ -0,0 +1,64 @@ +import abc + +class BaseImage(object): + """ + Base QRCode image output class. + """ + kind = None + allowed_kinds = None + + def __init__(self, border, width, box_size, *args, **kwargs): + self.border = border + self.width = width + self.box_size = box_size + self.pixel_size = (self.width + self.border*2) * self.box_size + self._img = self.new_image(**kwargs) + + @abc.abstractmethod + def drawrect(self, row, col): + """ + Draw a single rectangle of the QR code. + """ + + @abc.abstractmethod + def save(self, stream, kind=None): + """ + Save the image file. + """ + + def pixel_box(self, row, col): + """ + A helper method for pixel-based image generators that specifies the + four pixel coordinates for a single rect. + """ + x = (col + self.border) * self.box_size + y = (row + self.border) * self.box_size + return [(x, y), (x + self.box_size - 1, y + self.box_size - 1)] + + @abc.abstractmethod + def new_image(self, **kwargs): + """ + Build the image class. Subclasses should return the class created. + """ + + def get_image(self, **kwargs): + """ + Return the image class for further processing. + """ + return self._img + + def check_kind(self, kind, transform=None): + """ + Get the image type. + """ + if kind is None: + kind = self.kind + allowed = not self.allowed_kinds or kind in self.allowed_kinds + if transform: + kind = transform(kind) + if not allowed: + allowed = kind in self.allowed_kinds + if not allowed: + raise ValueError( + "Cannot set %s type to %s" % (type(self).__name__, kind)) + return kind diff --git a/source/pythonpath/qrcode/image/pil.py b/source/pythonpath/qrcode/image/pil.py new file mode 100644 index 0000000..3e92bd7 --- /dev/null +++ b/source/pythonpath/qrcode/image/pil.py @@ -0,0 +1,52 @@ +# Needed on case-insensitive filesystems +from __future__ import absolute_import + +# Try to import PIL in either of the two ways it can be installed. +try: + from PIL import Image, ImageDraw +except ImportError: # pragma: no cover + import Image + import ImageDraw + +import qrcode.image.base + + +class PilImage(qrcode.image.base.BaseImage): + """ + PIL image builder, default format is PNG. + """ + kind = "PNG" + + def new_image(self, **kwargs): + back_color = kwargs.get("back_color", "white") + fill_color = kwargs.get("fill_color", "black") + + if fill_color.lower() != "black" or back_color.lower() != "white": + if back_color.lower() == "transparent": + mode = "RGBA" + back_color = None + else: + mode = "RGB" + else: + mode = "1" + # L mode (1 mode) color = (r*299 + g*587 + b*114)//1000 + if fill_color.lower() == "black": fill_color = 0 + if back_color.lower() == "white": back_color = 255 + + img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color) + self.fill_color = fill_color + self._idr = ImageDraw.Draw(img) + return img + + def drawrect(self, row, col): + box = self.pixel_box(row, col) + self._idr.rectangle(box, fill=self.fill_color) + + def save(self, stream, format=None, **kwargs): + kind = kwargs.pop("kind", self.kind) + if format is None: + format = kind + self._img.save(stream, format=format, **kwargs) + + def __getattr__(self, name): + return getattr(self._img, name) diff --git a/source/pythonpath/qrcode/image/pure.py b/source/pythonpath/qrcode/image/pure.py new file mode 100644 index 0000000..34f75fe --- /dev/null +++ b/source/pythonpath/qrcode/image/pure.py @@ -0,0 +1,49 @@ +from pymaging import Image +from pymaging.colors import RGB +from pymaging.formats import registry +from pymaging.shapes import Line +from pymaging.webcolors import Black, White +from pymaging_png.png import PNG + +import qrcode.image.base + + +class PymagingImage(qrcode.image.base.BaseImage): + """ + pymaging image builder, default format is PNG. + """ + kind = "PNG" + allowed_kinds = ("PNG",) + + def __init__(self, *args, **kwargs): + """ + Register PNG with pymaging. + """ + registry.formats = [] + registry.names = {} + registry._populate() + registry.register(PNG) + + super(PymagingImage, self).__init__(*args, **kwargs) + + def new_image(self, **kwargs): + return Image.new(RGB, self.pixel_size, self.pixel_size, White) + + def drawrect(self, row, col): + (x, y), (x2, y2) = self.pixel_box(row, col) + for r in range(self.box_size): + line_y = y + r + line = Line(x, line_y, x2, line_y) + self._img.draw(line, Black) + + def save(self, stream, kind=None): + self._img.save(stream, self.check_kind(kind)) + + def check_kind(self, kind, transform=None, **kwargs): + """ + pymaging (pymaging_png at least) uses lower case for the type. + """ + if transform is None: + transform = lambda x: x.lower() + return super(PymagingImage, self).check_kind( + kind, transform=transform, **kwargs) diff --git a/source/pythonpath/qrcode/image/svg.py b/source/pythonpath/qrcode/image/svg.py new file mode 100644 index 0000000..e99a66f --- /dev/null +++ b/source/pythonpath/qrcode/image/svg.py @@ -0,0 +1,159 @@ +from decimal import Decimal +# On Python 2.6 must install lxml since the older xml.etree.ElementTree +# version can not be used to create SVG images. +try: + import lxml.etree as ET +except ImportError: + import xml.etree.ElementTree as ET +import qrcode.image.base + + +class SvgFragmentImage(qrcode.image.base.BaseImage): + """ + SVG image builder + + Creates a QR-code image as a SVG document fragment. + """ + + _SVG_namespace = "http://www.w3.org/2000/svg" + kind = "SVG" + allowed_kinds = ("SVG",) + + def __init__(self, *args, **kwargs): + ET.register_namespace("svg", self._SVG_namespace) + super(SvgFragmentImage, self).__init__(*args, **kwargs) + # Save the unit size, for example the default box_size of 10 is '1mm'. + self.unit_size = self.units(self.box_size) + + def drawrect(self, row, col): + self._img.append(self._rect(row, col)) + + def units(self, pixels, text=True): + """ + A box_size of 10 (default) equals 1mm. + """ + units = Decimal(pixels) / 10 + if not text: + return units + return '%smm' % units + + def save(self, stream, kind=None): + self.check_kind(kind=kind) + self._write(stream) + + def new_image(self, **kwargs): + return self._svg() + + def _svg(self, tag=None, version='1.1', **kwargs): + if tag is None: + tag = ET.QName(self._SVG_namespace, "svg") + dimension = self.units(self.pixel_size) + return ET.Element( + tag, width=dimension, height=dimension, version=version, + **kwargs) + + def _rect(self, row, col, tag=None): + if tag is None: + tag = ET.QName(self._SVG_namespace, "rect") + x, y = self.pixel_box(row, col)[0] + return ET.Element( + tag, x=self.units(x), y=self.units(y), + width=self.unit_size, height=self.unit_size) + + def _write(self, stream): + ET.ElementTree(self._img).write(stream, xml_declaration=False) + + +class SvgImage(SvgFragmentImage): + """ + Standalone SVG image builder + + Creates a QR-code image as a standalone SVG document. + """ + background = None + + def _svg(self, tag='svg', **kwargs): + svg = super(SvgImage, self)._svg(tag=tag, **kwargs) + svg.set("xmlns", self._SVG_namespace) + if self.background: + svg.append( + ET.Element( + 'rect', fill=self.background, x='0', y='0', width='100%', + height='100%')) + return svg + + def _rect(self, row, col): + return super(SvgImage, self)._rect(row, col, tag="rect") + + def _write(self, stream): + ET.ElementTree(self._img).write(stream, encoding="UTF-8", + xml_declaration=True) + + +class SvgPathImage(SvgImage): + """ + SVG image builder with one single element (removes white spaces + between individual QR points). + """ + + QR_PATH_STYLE = 'fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none' + + def __init__(self, *args, **kwargs): + self._points = set() + super(SvgPathImage, self).__init__(*args, **kwargs) + + def _svg(self, viewBox=None, **kwargs): + if viewBox is None: + dimension = self.units(self.pixel_size, text=False) + viewBox = '0 0 %(d)s %(d)s' % {'d': dimension} + return super(SvgPathImage, self)._svg(viewBox=viewBox, **kwargs) + + def drawrect(self, row, col): + # (x, y) + self._points.add((col, row)) + + def _generate_subpaths(self): + """Generates individual QR points as subpaths""" + + rect_size = self.units(self.box_size, text=False) + + for point in self._points: + x_base = self.units( + (point[0]+self.border)*self.box_size, text=False) + y_base = self.units( + (point[1]+self.border)*self.box_size, text=False) + + yield ( + 'M %(x0)s %(y0)s L %(x0)s %(y1)s L %(x1)s %(y1)s L %(x1)s ' + '%(y0)s z' % dict( + x0=x_base, y0=y_base, + x1=x_base+rect_size, y1=y_base+rect_size, + )) + + def make_path(self): + subpaths = self._generate_subpaths() + + return ET.Element( + ET.QName("path"), + style=self.QR_PATH_STYLE, + d=' '.join(subpaths), + id="qr-path" + ) + + def _write(self, stream): + self._img.append(self.make_path()) + super(SvgPathImage, self)._write(stream) + + +class SvgFillImage(SvgImage): + """ + An SvgImage that fills the background to white. + """ + background = 'white' + + +class SvgPathFillImage(SvgPathImage): + """ + An SvgPathImage that fills the background to white. + """ + background = 'white' diff --git a/source/pythonpath/qrcode/main.py b/source/pythonpath/qrcode/main.py new file mode 100644 index 0000000..7317372 --- /dev/null +++ b/source/pythonpath/qrcode/main.py @@ -0,0 +1,434 @@ +from qrcode import constants, exceptions, util +from qrcode.image.base import BaseImage + +import six +from bisect import bisect_left + + +def make(data=None, **kwargs): + qr = QRCode(**kwargs) + qr.add_data(data) + return qr.make_image() + + +def _check_box_size(size): + if int(size) <= 0: + raise ValueError( + "Invalid box size (was %s, expected larger than 0)" % size) + + +def _check_mask_pattern(mask_pattern): + if mask_pattern is None: + return + if not isinstance(mask_pattern, int): + raise TypeError( + "Invalid mask pattern (was %s, expected int)" % type(mask_pattern)) + if mask_pattern < 0 or mask_pattern > 7: + raise ValueError( + "Mask pattern should be in range(8) (got %s)" % mask_pattern) + + +class QRCode(object): + + def __init__(self, version=None, + error_correction=constants.ERROR_CORRECT_M, + box_size=10, border=4, + image_factory=None, + mask_pattern=None): + _check_box_size(box_size) + self.version = version and int(version) + self.error_correction = int(error_correction) + self.box_size = int(box_size) + # Spec says border should be at least four boxes wide, but allow for + # any (e.g. for producing printable QR codes). + self.border = int(border) + _check_mask_pattern(mask_pattern) + self.mask_pattern = mask_pattern + self.image_factory = image_factory + if image_factory is not None: + assert issubclass(image_factory, BaseImage) + self.clear() + + def clear(self): + """ + Reset the internal data. + """ + self.modules = None + self.modules_count = 0 + self.data_cache = None + self.data_list = [] + + def add_data(self, data, optimize=20): + """ + Add data to this QR Code. + + :param optimize: Data will be split into multiple chunks to optimize + the QR size by finding to more compressed modes of at least this + length. Set to ``0`` to avoid optimizing at all. + """ + if isinstance(data, util.QRData): + self.data_list.append(data) + else: + if optimize: + self.data_list.extend( + util.optimal_data_chunks(data, minimum=optimize)) + else: + self.data_list.append(util.QRData(data)) + self.data_cache = None + + def make(self, fit=True): + """ + Compile the data into a QR Code array. + + :param fit: If ``True`` (or if a size has not been provided), find the + best fit for the data to avoid data overflow errors. + """ + if fit or (self.version is None): + self.best_fit(start=self.version) + if self.mask_pattern is None: + self.makeImpl(False, self.best_mask_pattern()) + else: + self.makeImpl(False, self.mask_pattern) + + def makeImpl(self, test, mask_pattern): + util.check_version(self.version) + self.modules_count = self.version * 4 + 17 + self.modules = [None] * self.modules_count + + for row in range(self.modules_count): + + self.modules[row] = [None] * self.modules_count + + for col in range(self.modules_count): + self.modules[row][col] = None # (col + row) % 3 + + self.setup_position_probe_pattern(0, 0) + self.setup_position_probe_pattern(self.modules_count - 7, 0) + self.setup_position_probe_pattern(0, self.modules_count - 7) + self.setup_position_adjust_pattern() + self.setup_timing_pattern() + self.setup_type_info(test, mask_pattern) + + if self.version >= 7: + self.setup_type_number(test) + + if self.data_cache is None: + self.data_cache = util.create_data( + self.version, self.error_correction, self.data_list) + self.map_data(self.data_cache, mask_pattern) + + def setup_position_probe_pattern(self, row, col): + for r in range(-1, 8): + + if row + r <= -1 or self.modules_count <= row + r: + continue + + for c in range(-1, 8): + + if col + c <= -1 or self.modules_count <= col + c: + continue + + if (0 <= r and r <= 6 and (c == 0 or c == 6) + or (0 <= c and c <= 6 and (r == 0 or r == 6)) + or (2 <= r and r <= 4 and 2 <= c and c <= 4)): + self.modules[row + r][col + c] = True + else: + self.modules[row + r][col + c] = False + + def best_fit(self, start=None): + """ + Find the minimum size required to fit in the data. + """ + if start is None: + start = 1 + util.check_version(start) + + # Corresponds to the code in util.create_data, except we don't yet know + # version, so optimistically assume start and check later + mode_sizes = util.mode_sizes_for_version(start) + buffer = util.BitBuffer() + for data in self.data_list: + buffer.put(data.mode, 4) + buffer.put(len(data), mode_sizes[data.mode]) + data.write(buffer) + + needed_bits = len(buffer) + self.version = bisect_left(util.BIT_LIMIT_TABLE[self.error_correction], + needed_bits, start) + if self.version == 41: + raise exceptions.DataOverflowError() + + # Now check whether we need more bits for the mode sizes, recursing if + # our guess was too low + if mode_sizes is not util.mode_sizes_for_version(self.version): + self.best_fit(start=self.version) + return self.version + + def best_mask_pattern(self): + """ + Find the most efficient mask pattern. + """ + min_lost_point = 0 + pattern = 0 + + for i in range(8): + self.makeImpl(True, i) + + lost_point = util.lost_point(self.modules) + + if i == 0 or min_lost_point > lost_point: + min_lost_point = lost_point + pattern = i + + return pattern + + def print_tty(self, out=None): + """ + Output the QR Code only using TTY colors. + + If the data has not been compiled yet, make it first. + """ + if out is None: + import sys + out = sys.stdout + + if not out.isatty(): + raise OSError("Not a tty") + + if self.data_cache is None: + self.make() + + modcount = self.modules_count + out.write("\x1b[1;47m" + (" " * (modcount * 2 + 4)) + "\x1b[0m\n") + for r in range(modcount): + out.write("\x1b[1;47m \x1b[40m") + for c in range(modcount): + if self.modules[r][c]: + out.write(" ") + else: + out.write("\x1b[1;47m \x1b[40m") + out.write("\x1b[1;47m \x1b[0m\n") + out.write("\x1b[1;47m" + (" " * (modcount * 2 + 4)) + "\x1b[0m\n") + out.flush() + + def print_ascii(self, out=None, tty=False, invert=False): + """ + Output the QR Code using ASCII characters. + + :param tty: use fixed TTY color codes (forces invert=True) + :param invert: invert the ASCII characters (solid <-> transparent) + """ + if out is None: + import sys + if sys.version_info < (2, 7): + # On Python versions 2.6 and earlier, stdout tries to encode + # strings using ASCII rather than stdout.encoding, so use this + # workaround. + import codecs + out = codecs.getwriter(sys.stdout.encoding)(sys.stdout) + else: + out = sys.stdout + + if tty and not out.isatty(): + raise OSError("Not a tty") + + if self.data_cache is None: + self.make() + + modcount = self.modules_count + codes = [six.int2byte(code).decode('cp437') + for code in (255, 223, 220, 219)] + if tty: + invert = True + if invert: + codes.reverse() + + def get_module(x, y): + if (invert and self.border and + max(x, y) >= modcount+self.border): + return 1 + if min(x, y) < 0 or max(x, y) >= modcount: + return 0 + return self.modules[x][y] + + for r in range(-self.border, modcount+self.border, 2): + if tty: + if not invert or r < modcount+self.border-1: + out.write('\x1b[48;5;232m') # Background black + out.write('\x1b[38;5;255m') # Foreground white + for c in range(-self.border, modcount+self.border): + pos = get_module(r, c) + (get_module(r+1, c) << 1) + out.write(codes[pos]) + if tty: + out.write('\x1b[0m') + out.write('\n') + out.flush() + + def make_image(self, image_factory=None, **kwargs): + """ + Make an image from the QR Code data. + + If the data has not been compiled yet, make it first. + """ + _check_box_size(self.box_size) + if self.data_cache is None: + self.make() + + if image_factory is not None: + assert issubclass(image_factory, BaseImage) + else: + image_factory = self.image_factory + if image_factory is None: + # Use PIL by default + from qrcode.image.pil import PilImage + image_factory = PilImage + + im = image_factory( + self.border, self.modules_count, self.box_size, **kwargs) + for r in range(self.modules_count): + for c in range(self.modules_count): + if self.modules[r][c]: + im.drawrect(r, c) + return im + + def setup_timing_pattern(self): + for r in range(8, self.modules_count - 8): + if self.modules[r][6] is not None: + continue + self.modules[r][6] = (r % 2 == 0) + + for c in range(8, self.modules_count - 8): + if self.modules[6][c] is not None: + continue + self.modules[6][c] = (c % 2 == 0) + + def setup_position_adjust_pattern(self): + pos = util.pattern_position(self.version) + + for i in range(len(pos)): + + for j in range(len(pos)): + + row = pos[i] + col = pos[j] + + if self.modules[row][col] is not None: + continue + + for r in range(-2, 3): + + for c in range(-2, 3): + + if (r == -2 or r == 2 or c == -2 or c == 2 or + (r == 0 and c == 0)): + self.modules[row + r][col + c] = True + else: + self.modules[row + r][col + c] = False + + def setup_type_number(self, test): + bits = util.BCH_type_number(self.version) + + for i in range(18): + mod = (not test and ((bits >> i) & 1) == 1) + self.modules[i // 3][i % 3 + self.modules_count - 8 - 3] = mod + + for i in range(18): + mod = (not test and ((bits >> i) & 1) == 1) + self.modules[i % 3 + self.modules_count - 8 - 3][i // 3] = mod + + def setup_type_info(self, test, mask_pattern): + data = (self.error_correction << 3) | mask_pattern + bits = util.BCH_type_info(data) + + # vertical + for i in range(15): + + mod = (not test and ((bits >> i) & 1) == 1) + + if i < 6: + self.modules[i][8] = mod + elif i < 8: + self.modules[i + 1][8] = mod + else: + self.modules[self.modules_count - 15 + i][8] = mod + + # horizontal + for i in range(15): + + mod = (not test and ((bits >> i) & 1) == 1) + + if i < 8: + self.modules[8][self.modules_count - i - 1] = mod + elif i < 9: + self.modules[8][15 - i - 1 + 1] = mod + else: + self.modules[8][15 - i - 1] = mod + + # fixed module + self.modules[self.modules_count - 8][8] = (not test) + + def map_data(self, data, mask_pattern): + inc = -1 + row = self.modules_count - 1 + bitIndex = 7 + byteIndex = 0 + + mask_func = util.mask_func(mask_pattern) + + data_len = len(data) + + for col in six.moves.xrange(self.modules_count - 1, 0, -2): + + if col <= 6: + col -= 1 + + col_range = (col, col-1) + + while True: + + for c in col_range: + + if self.modules[row][c] is None: + + dark = False + + if byteIndex < data_len: + dark = (((data[byteIndex] >> bitIndex) & 1) == 1) + + if mask_func(row, c): + dark = not dark + + self.modules[row][c] = dark + bitIndex -= 1 + + if bitIndex == -1: + byteIndex += 1 + bitIndex = 7 + + row += inc + + if row < 0 or self.modules_count <= row: + row -= inc + inc = -inc + break + + def get_matrix(self): + """ + Return the QR Code as a multidimensonal array, including the border. + + To return the array without a border, set ``self.border`` to 0 first. + """ + if self.data_cache is None: + self.make() + + if not self.border: + return self.modules + + width = len(self.modules) + self.border*2 + code = [[False]*width] * self.border + x_border = [False]*self.border + for module in self.modules: + code.append(x_border + module + x_border) + code += [[False]*width] * self.border + + return code diff --git a/source/pythonpath/qrcode/release.py b/source/pythonpath/qrcode/release.py new file mode 100644 index 0000000..4cc4c19 --- /dev/null +++ b/source/pythonpath/qrcode/release.py @@ -0,0 +1,41 @@ +""" +This file provides zest.releaser entrypoints using when releasing new +qrcode versions. +""" +import os +import re +import datetime + + +def update_manpage(data): + """ + Update the version in the manpage document. + """ + if data['name'] != 'qrcode': + return + + base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + filename = os.path.join(base_dir, 'doc', 'qr.1') + with open(filename, 'r') as f: + lines = f.readlines() + + changed = False + for i, line in enumerate(lines): + if not line.startswith('.TH '): + continue + parts = re.split(r'"([^"]*)"', line) + if len(parts) < 5: + continue + changed = parts[3] != data['new_version'] + if changed: + # Update version + parts[3] = data['new_version'] + # Update date + parts[1] = datetime.datetime.now().strftime('%-d %b %Y') + lines[i] = '"'.join(parts) + break + + if changed: + with open(filename, 'w') as f: + for line in lines: + f.write(line) diff --git a/source/pythonpath/qrcode/util.py b/source/pythonpath/qrcode/util.py new file mode 100644 index 0000000..58f3d21 --- /dev/null +++ b/source/pythonpath/qrcode/util.py @@ -0,0 +1,599 @@ +import re +import math + +import six +from six.moves import xrange + +from qrcode import base, exceptions, LUT + +# QR encoding modes. +MODE_NUMBER = 1 << 0 +MODE_ALPHA_NUM = 1 << 1 +MODE_8BIT_BYTE = 1 << 2 +MODE_KANJI = 1 << 3 + +# Encoding mode sizes. +MODE_SIZE_SMALL = { + MODE_NUMBER: 10, + MODE_ALPHA_NUM: 9, + MODE_8BIT_BYTE: 8, + MODE_KANJI: 8, +} +MODE_SIZE_MEDIUM = { + MODE_NUMBER: 12, + MODE_ALPHA_NUM: 11, + MODE_8BIT_BYTE: 16, + MODE_KANJI: 10, +} +MODE_SIZE_LARGE = { + MODE_NUMBER: 14, + MODE_ALPHA_NUM: 13, + MODE_8BIT_BYTE: 16, + MODE_KANJI: 12, +} + +ALPHA_NUM = six.b('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:') +RE_ALPHA_NUM = re.compile(six.b('^[') + re.escape(ALPHA_NUM) + six.b(r']*\Z')) + +# The number of bits for numeric delimited data lengths. +NUMBER_LENGTH = {3: 10, 2: 7, 1: 4} + +PATTERN_POSITION_TABLE = [ + [], + [6, 18], + [6, 22], + [6, 26], + [6, 30], + [6, 34], + [6, 22, 38], + [6, 24, 42], + [6, 26, 46], + [6, 28, 50], + [6, 30, 54], + [6, 32, 58], + [6, 34, 62], + [6, 26, 46, 66], + [6, 26, 48, 70], + [6, 26, 50, 74], + [6, 30, 54, 78], + [6, 30, 56, 82], + [6, 30, 58, 86], + [6, 34, 62, 90], + [6, 28, 50, 72, 94], + [6, 26, 50, 74, 98], + [6, 30, 54, 78, 102], + [6, 28, 54, 80, 106], + [6, 32, 58, 84, 110], + [6, 30, 58, 86, 114], + [6, 34, 62, 90, 118], + [6, 26, 50, 74, 98, 122], + [6, 30, 54, 78, 102, 126], + [6, 26, 52, 78, 104, 130], + [6, 30, 56, 82, 108, 134], + [6, 34, 60, 86, 112, 138], + [6, 30, 58, 86, 114, 142], + [6, 34, 62, 90, 118, 146], + [6, 30, 54, 78, 102, 126, 150], + [6, 24, 50, 76, 102, 128, 154], + [6, 28, 54, 80, 106, 132, 158], + [6, 32, 58, 84, 110, 136, 162], + [6, 26, 54, 82, 110, 138, 166], + [6, 30, 58, 86, 114, 142, 170] +] + +G15 = ( + (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | + (1 << 0)) +G18 = ( + (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | + (1 << 2) | (1 << 0)) +G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) + +PAD0 = 0xEC +PAD1 = 0x11 + +# Precompute bit count limits, indexed by error correction level and code size +_data_count = lambda block: block.data_count +BIT_LIMIT_TABLE = [ + [0] + [8*sum(map(_data_count, base.rs_blocks(version, error_correction))) + for version in xrange(1, 41)] + for error_correction in xrange(4) +] + + +def BCH_type_info(data): + d = data << 10 + while BCH_digit(d) - BCH_digit(G15) >= 0: + d ^= (G15 << (BCH_digit(d) - BCH_digit(G15))) + + return ((data << 10) | d) ^ G15_MASK + + +def BCH_type_number(data): + d = data << 12 + while BCH_digit(d) - BCH_digit(G18) >= 0: + d ^= (G18 << (BCH_digit(d) - BCH_digit(G18))) + return (data << 12) | d + + +def BCH_digit(data): + digit = 0 + while data != 0: + digit += 1 + data >>= 1 + return digit + + +def pattern_position(version): + return PATTERN_POSITION_TABLE[version - 1] + + +def mask_func(pattern): + """ + Return the mask function for the given mask pattern. + """ + if pattern == 0: # 000 + return lambda i, j: (i + j) % 2 == 0 + if pattern == 1: # 001 + return lambda i, j: i % 2 == 0 + if pattern == 2: # 010 + return lambda i, j: j % 3 == 0 + if pattern == 3: # 011 + return lambda i, j: (i + j) % 3 == 0 + if pattern == 4: # 100 + return lambda i, j: (math.floor(i / 2) + math.floor(j / 3)) % 2 == 0 + if pattern == 5: # 101 + return lambda i, j: (i * j) % 2 + (i * j) % 3 == 0 + if pattern == 6: # 110 + return lambda i, j: ((i * j) % 2 + (i * j) % 3) % 2 == 0 + if pattern == 7: # 111 + return lambda i, j: ((i * j) % 3 + (i + j) % 2) % 2 == 0 + raise TypeError("Bad mask pattern: " + pattern) # pragma: no cover + + +def mode_sizes_for_version(version): + if version < 10: + return MODE_SIZE_SMALL + elif version < 27: + return MODE_SIZE_MEDIUM + else: + return MODE_SIZE_LARGE + + +def length_in_bits(mode, version): + if mode not in ( + MODE_NUMBER, MODE_ALPHA_NUM, MODE_8BIT_BYTE, MODE_KANJI): + raise TypeError("Invalid mode (%s)" % mode) # pragma: no cover + + check_version(version) + + return mode_sizes_for_version(version)[mode] + + +def check_version(version): + if version < 1 or version > 40: + raise ValueError( + "Invalid version (was %s, expected 1 to 40)" % version) + + +def lost_point(modules): + modules_count = len(modules) + + lost_point = 0 + + lost_point = _lost_point_level1(modules, modules_count) + lost_point += _lost_point_level2(modules, modules_count) + lost_point += _lost_point_level3(modules, modules_count) + lost_point += _lost_point_level4(modules, modules_count) + + return lost_point + + +def _lost_point_level1(modules, modules_count): + lost_point = 0 + + modules_range = xrange(modules_count) + container = [0] * (modules_count + 1) + + for row in modules_range: + this_row = modules[row] + previous_color = this_row[0] + length = 0 + for col in modules_range: + if this_row[col] == previous_color: + length += 1 + else: + if length >= 5: + container[length] += 1 + length = 1 + previous_color = this_row[col] + if length >= 5: + container[length] += 1 + + for col in modules_range: + previous_color = modules[0][col] + length = 0 + for row in modules_range: + if modules[row][col] == previous_color: + length += 1 + else: + if length >= 5: + container[length] += 1 + length = 1 + previous_color = modules[row][col] + if length >= 5: + container[length] += 1 + + lost_point += sum(container[each_length] * (each_length - 2) + for each_length in xrange(5, modules_count + 1)) + + return lost_point + + +def _lost_point_level2(modules, modules_count): + lost_point = 0 + + modules_range = xrange(modules_count - 1) + for row in modules_range: + this_row = modules[row] + next_row = modules[row + 1] + # use iter() and next() to skip next four-block. e.g. + # d a f if top-right a != b botton-right, + # c b e then both abcd and abef won't lost any point. + modules_range_iter = iter(modules_range) + for col in modules_range_iter: + top_right = this_row[col + 1] + if top_right != next_row[col + 1]: + # reduce 33.3% of runtime via next(). + # None: raise nothing if there is no next item. + next(modules_range_iter, None) + elif top_right != this_row[col]: + continue + elif top_right != next_row[col]: + continue + else: + lost_point += 3 + + return lost_point + + +def _lost_point_level3(modules, modules_count): + # 1 : 1 : 3 : 1 : 1 ratio (dark:light:dark:light:dark) pattern in + # row/column, preceded or followed by light area 4 modules wide. From ISOIEC. + # pattern1: 10111010000 + # pattern2: 00001011101 + modules_range = xrange(modules_count) + modules_range_short = xrange(modules_count-10) + lost_point = 0 + + for row in modules_range: + this_row = modules[row] + modules_range_short_iter = iter(modules_range_short) + col = 0 + for col in modules_range_short_iter: + if ( + not this_row[col + 1] + and this_row[col + 4] + and not this_row[col + 5] + and this_row[col + 6] + and not this_row[col + 9] + and ( + this_row[col + 0] + and this_row[col + 2] + and this_row[col + 3] + and not this_row[col + 7] + and not this_row[col + 8] + and not this_row[col + 10] + or + not this_row[col + 0] + and not this_row[col + 2] + and not this_row[col + 3] + and this_row[col + 7] + and this_row[col + 8] + and this_row[col + 10] + ) + ): + lost_point += 40 +# horspool algorithm. +# if this_row[col + 10] == True, pattern1 shift 4, pattern2 shift 2. So min=2. +# if this_row[col + 10] == False, pattern1 shift 1, pattern2 shift 1. So min=1. + if this_row[col + 10]: + next(modules_range_short_iter, None) + + for col in modules_range: + modules_range_short_iter = iter(modules_range_short) + row = 0 + for row in modules_range_short_iter: + if ( + not modules[row + 1][col] + and modules[row + 4][col] + and not modules[row + 5][col] + and modules[row + 6][col] + and not modules[row + 9][col] + and ( + modules[row + 0][col] + and modules[row + 2][col] + and modules[row + 3][col] + and not modules[row + 7][col] + and not modules[row + 8][col] + and not modules[row + 10][col] + or + not modules[row + 0][col] + and not modules[row + 2][col] + and not modules[row + 3][col] + and modules[row + 7][col] + and modules[row + 8][col] + and modules[row + 10][col] + ) + ): + lost_point += 40 + if modules[row + 10][col]: + next(modules_range_short_iter, None) + + return lost_point + + +def _lost_point_level4(modules, modules_count): + dark_count = sum(map(sum, modules)) + percent = float(dark_count) / (modules_count**2) + # Every 5% departure from 50%, rating++ + rating = int(abs(percent * 100 - 50) / 5) + return rating * 10 + + +def optimal_data_chunks(data, minimum=4): + """ + An iterator returning QRData chunks optimized to the data content. + + :param minimum: The minimum number of bytes in a row to split as a chunk. + """ + data = to_bytestring(data) + num_pattern = six.b(r'\d') + alpha_pattern = six.b('[') + re.escape(ALPHA_NUM) + six.b(']') + if len(data) <= minimum: + num_pattern = re.compile(six.b('^') + num_pattern + six.b('+$')) + alpha_pattern = re.compile(six.b('^') + alpha_pattern + six.b('+$')) + else: + re_repeat = ( + six.b('{') + six.text_type(minimum).encode('ascii') + six.b(',}')) + num_pattern = re.compile(num_pattern + re_repeat) + alpha_pattern = re.compile(alpha_pattern + re_repeat) + num_bits = _optimal_split(data, num_pattern) + for is_num, chunk in num_bits: + if is_num: + yield QRData(chunk, mode=MODE_NUMBER, check_data=False) + else: + for is_alpha, sub_chunk in _optimal_split(chunk, alpha_pattern): + if is_alpha: + mode = MODE_ALPHA_NUM + else: + mode = MODE_8BIT_BYTE + yield QRData(sub_chunk, mode=mode, check_data=False) + + +def _optimal_split(data, pattern): + while data: + match = re.search(pattern, data) + if not match: + break + start, end = match.start(), match.end() + if start: + yield False, data[:start] + yield True, data[start:end] + data = data[end:] + if data: + yield False, data + + +def to_bytestring(data): + """ + Convert data to a (utf-8 encoded) byte-string if it isn't a byte-string + already. + """ + if not isinstance(data, six.binary_type): + data = six.text_type(data).encode('utf-8') + return data + + +def optimal_mode(data): + """ + Calculate the optimal mode for this chunk of data. + """ + if data.isdigit(): + return MODE_NUMBER + if RE_ALPHA_NUM.match(data): + return MODE_ALPHA_NUM + return MODE_8BIT_BYTE + + +class QRData(object): + """ + Data held in a QR compatible format. + + Doesn't currently handle KANJI. + """ + + def __init__(self, data, mode=None, check_data=True): + """ + If ``mode`` isn't provided, the most compact QR data type possible is + chosen. + """ + if check_data: + data = to_bytestring(data) + + if mode is None: + self.mode = optimal_mode(data) + else: + self.mode = mode + if mode not in (MODE_NUMBER, MODE_ALPHA_NUM, MODE_8BIT_BYTE): + raise TypeError("Invalid mode (%s)" % mode) # pragma: no cover + if check_data and mode < optimal_mode(data): # pragma: no cover + raise ValueError( + "Provided data can not be represented in mode " + "{0}".format(mode)) + + self.data = data + + def __len__(self): + return len(self.data) + + def write(self, buffer): + if self.mode == MODE_NUMBER: + for i in xrange(0, len(self.data), 3): + chars = self.data[i:i + 3] + bit_length = NUMBER_LENGTH[len(chars)] + buffer.put(int(chars), bit_length) + elif self.mode == MODE_ALPHA_NUM: + for i in xrange(0, len(self.data), 2): + chars = self.data[i:i + 2] + if len(chars) > 1: + buffer.put( + ALPHA_NUM.find(chars[0]) * 45 + + ALPHA_NUM.find(chars[1]), 11) + else: + buffer.put(ALPHA_NUM.find(chars), 6) + else: + if six.PY3: + # Iterating a bytestring in Python 3 returns an integer, + # no need to ord(). + data = self.data + else: + data = [ord(c) for c in self.data] + for c in data: + buffer.put(c, 8) + + def __repr__(self): + return repr(self.data) + + +class BitBuffer(object): + + def __init__(self): + self.buffer = [] + self.length = 0 + + def __repr__(self): + return ".".join([str(n) for n in self.buffer]) + + def get(self, index): + buf_index = math.floor(index / 8) + return ((self.buffer[buf_index] >> (7 - index % 8)) & 1) == 1 + + def put(self, num, length): + for i in range(length): + self.put_bit(((num >> (length - i - 1)) & 1) == 1) + + def __len__(self): + return self.length + + def put_bit(self, bit): + buf_index = self.length // 8 + if len(self.buffer) <= buf_index: + self.buffer.append(0) + if bit: + self.buffer[buf_index] |= (0x80 >> (self.length % 8)) + self.length += 1 + + +def create_bytes(buffer, rs_blocks): + offset = 0 + + maxDcCount = 0 + maxEcCount = 0 + + dcdata = [0] * len(rs_blocks) + ecdata = [0] * len(rs_blocks) + + for r in range(len(rs_blocks)): + + dcCount = rs_blocks[r].data_count + ecCount = rs_blocks[r].total_count - dcCount + + maxDcCount = max(maxDcCount, dcCount) + maxEcCount = max(maxEcCount, ecCount) + + dcdata[r] = [0] * dcCount + + for i in range(len(dcdata[r])): + dcdata[r][i] = 0xff & buffer.buffer[i + offset] + offset += dcCount + + # Get error correction polynomial. + if ecCount in LUT.rsPoly_LUT: + rsPoly = base.Polynomial(LUT.rsPoly_LUT[ecCount], 0) + else: + rsPoly = base.Polynomial([1], 0) + for i in range(ecCount): + rsPoly = rsPoly * base.Polynomial([1, base.gexp(i)], 0) + + rawPoly = base.Polynomial(dcdata[r], len(rsPoly) - 1) + + modPoly = rawPoly % rsPoly + ecdata[r] = [0] * (len(rsPoly) - 1) + for i in range(len(ecdata[r])): + modIndex = i + len(modPoly) - len(ecdata[r]) + if (modIndex >= 0): + ecdata[r][i] = modPoly[modIndex] + else: + ecdata[r][i] = 0 + + totalCodeCount = 0 + for rs_block in rs_blocks: + totalCodeCount += rs_block.total_count + + data = [None] * totalCodeCount + index = 0 + + for i in range(maxDcCount): + for r in range(len(rs_blocks)): + if i < len(dcdata[r]): + data[index] = dcdata[r][i] + index += 1 + + for i in range(maxEcCount): + for r in range(len(rs_blocks)): + if i < len(ecdata[r]): + data[index] = ecdata[r][i] + index += 1 + + return data + + +def create_data(version, error_correction, data_list): + + buffer = BitBuffer() + for data in data_list: + buffer.put(data.mode, 4) + buffer.put(len(data), length_in_bits(data.mode, version)) + data.write(buffer) + + # Calculate the maximum number of bits for the given version. + rs_blocks = base.rs_blocks(version, error_correction) + bit_limit = 0 + for block in rs_blocks: + bit_limit += block.data_count * 8 + + if len(buffer) > bit_limit: + raise exceptions.DataOverflowError( + "Code length overflow. Data size (%s) > size available (%s)" % + (len(buffer), bit_limit)) + + # Terminate the bits (add up to four 0s). + for i in range(min(bit_limit - len(buffer), 4)): + buffer.put_bit(False) + + # Delimit the string into 8-bit words, padding with 0s if necessary. + delimit = len(buffer) % 8 + if delimit: + for i in range(8 - delimit): + buffer.put_bit(False) + + # Add special alternating padding bitstrings until buffer is full. + bytes_to_fill = (bit_limit - len(buffer)) // 8 + for i in range(bytes_to_fill): + if i % 2 == 0: + buffer.put(PAD0, 8) + else: + buffer.put(PAD1, 8) + + return create_bytes(buffer, rs_blocks) diff --git a/source/registration/license_en.txt b/source/registration/license_en.txt new file mode 100644 index 0000000..0a88555 --- /dev/null +++ b/source/registration/license_en.txt @@ -0,0 +1,14 @@ +This file is part of ZAZBarCode. + + ZAZBarCode is free software: you can 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. + + ZAZBarCode is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with ZAZBarCode. If not, see . diff --git a/source/registration/license_es.txt b/source/registration/license_es.txt new file mode 100644 index 0000000..0a88555 --- /dev/null +++ b/source/registration/license_es.txt @@ -0,0 +1,14 @@ +This file is part of ZAZBarCode. + + ZAZBarCode is free software: you can 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. + + ZAZBarCode is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with ZAZBarCode. If not, see . diff --git a/zaz.py b/zaz.py new file mode 100644 index 0000000..7a0999f --- /dev/null +++ b/zaz.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 + +# == Rapid Develop Macros in LibreOffice == + +# ~ This file is part of ZAZ. + +# ~ ZAZ is free software: you can 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. + +# ~ ZAZ is distributed in the hope that it will be useful, +# ~ but WITHOUT ANY WARRANTY; without even the implied warranty of +# ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# ~ GNU General Public License for more details. + +# ~ You should have received a copy of the GNU General Public License +# ~ along with ZAZ. If not, see . + +import argparse +import os +import sys +from shutil import copyfile +from subprocess import call +import zipfile + +from conf import ( + DATA, + DIRS, + EXTENSION, + FILES, + INFO, + PATHS, + TYPE_EXTENSION, + log) + + +def _exists(path): + return os.path.exists(path) + + +def _join(*paths): + return os.path.join(*paths) + + +def _mkdir(path): + return os.mkdir(path) + + +def _save(path, data): + with open(path, 'w') as f: + f.write(data) + return + + +def _compress_oxt(): + log.info('Compress OXT extension...') + + path = DIRS['files'] + if not _exists(path): + _mkdir(path) + + path_oxt = _join(path, FILES['oxt']) + + z = zipfile.ZipFile(path_oxt, 'w', compression=zipfile.ZIP_DEFLATED) + root_len = len(os.path.abspath(DIRS['source'])) + for root, dirs, files in os.walk(DIRS['source']): + relative = os.path.abspath(root)[root_len:] + for f in files: + fullpath = _join(root, f) + file_name = _join(relative, f) + if file_name == FILES['idl']: + continue + z.write(fullpath, file_name, zipfile.ZIP_DEFLATED) + z.close() + + log.info('Extension OXT created sucesfully...') + return + + +def _install_and_test(): + path_oxt = (_join(DIRS['files'], FILES['oxt']),) + call(PATHS['install'] + path_oxt) + log.info('Install extension sucesfully...') + log.info('Start LibreOffice...') + call(PATHS['soffice']) + return + + +def _validate_new(): + path_source = DIRS['source'] + if not _exists(path_source): + return True + + msg = f'Path: {path_source}, exists, delete first' + log.error(msg) + return False + + +def _create_new_directories(): + path_source = DIRS['source'] + _mkdir(path_source) + path = _join(path_source, DIRS['meta']) + _mkdir(path) + path = _join(path_source, DIRS['description']) + _mkdir(path) + path = _join(path_source, DIRS['images']) + _mkdir(path) + path = _join(path_source, DIRS['registration']) + _mkdir(path) + + if FILES['easymacro'] or DIRS['pythonpath']: + path = _join(path_source, 'pythonpath') + _mkdir(path) + + path = DIRS['files'] + if not _exists(path): + _mkdir(path) + + msg = 'Created directories...' + log.info(msg) + return + + +def _create_new_files(): + path_source = DIRS['source'] + + for k, v in INFO.items(): + file_name = f'license_{k}.txt' + path = _join(path_source, DIRS['registration'], file_name) + _save(path, v['license']) + + if TYPE_EXTENSION > 1: + path = _join(path_source, FILES['idl']) + _save(path, DATA['idl']) + + path = _join(path_source, FILES['py']) + _save(path, DATA['py']) + + + msg = 'Created files...' + log.info(msg) + return + + +def _validate_update(): + if TYPE_EXTENSION == 1: + return True + + if not _exists(PATHS['idlc']): + msg = 'Binary: "idlc" not found' + log.error(msg) + return False + + if not _exists(PATHS['include']): + msg = 'Directory: "include" not found' + log.error(msg) + return False + + if not _exists(PATHS['regmerge']): + msg = 'Binary: "regmerge" not found' + log.error(msg) + return False + + path = _join(DIRS['source'], FILES['idl']) + if not _exists(path): + msg = f'File: "{FILES["idl"]}" not found' + log.error(msg) + return False + + return True + + +def _compile_idl(): + if TYPE_EXTENSION == 1: + return + + log.info('Compilate IDL...') + path_rdb = _join(DIRS['source'], FILES['rdb']) + path_urd = _join(DIRS['source'], FILES['urd']) + + path = _join(DIRS['source'], FILES['idl']) + call([PATHS['idlc'], '-I', PATHS['include'], path]) + call([PATHS['regmerge'], path_rdb, '/UCR', path_urd]) + os.remove(path_urd) + + log.info('Compilate IDL sucesfully...') + return + + +def _update_files(): + path_source = DIRS['source'] + + for k, v in INFO.items(): + file_name = FILES['ext_desc'].format(k) + path = _join(path_source, DIRS['description'], file_name) + _save(path, v['description']) + + path_logo = EXTENSION['icon'][0] + if _exists(path_logo): + file_name = EXTENSION['icon'][1] + path = _join(path_source, DIRS['images'], file_name) + copyfile(path_logo, path) + + files = os.listdir(DIRS['images']) + for f in files: + if f[-3:].lower() == 'bmp': + source = _join(DIRS['images'], f) + target = _join(path_source, DIRS['images'], f) + copyfile(source, target) + + if FILES['easymacro']: + source = 'easymacro.py' + target = _join(path_source, 'pythonpath', source) + copyfile(source, target) + + path = _join(path_source, DIRS['meta'], FILES['manifest']) + _save(path, DATA['manifest']) + + path = _join(path_source, FILES['addons']) + _save(path, DATA['addons']) + + path = _join(path_source, FILES['description']) + _save(path, DATA['description']) + + if TYPE_EXTENSION == 3: + path = _join(path_source, FILES['addin']) + _save(path, DATA['addin']) + + _compile_idl() + return + + +def _new(): + if not _validate_new(): + return + + _create_new_directories() + _create_new_files() + _update_files() + + msg = f"New extension: {EXTENSION['name']} make sucesfully...\n" + msg += '\tNow, you can install and test: zaz.py -i' + log.info(msg) + return + + +def main(args): + if args.new: + _new() + return + + if not _validate_update(): + return + + _update_files() + _compress_oxt() + + if args.install: + _install_and_test() + + log.info('Extension make sucesfully...') + return + + +def _process_command_line_arguments(): + parser = argparse.ArgumentParser( + description='Make LibreOffice extensions') + parser.add_argument('-i', '--install', dest='install', action='store_true', + default=False, required=False) + parser.add_argument('-n', '--new', dest='new', action='store_true', + default=False, required=False) + return parser.parse_args() + + +if __name__ == '__main__': + args = _process_command_line_arguments() + main(args) +